StreamReader to file?

2019-07-21 03:59发布

问题:

I have an input stream wrapped in a System.IO.StreamReader... I wish to write the content of the stream to a file (i.e. StreamWriter).

The length of the inputstream is unknown. Could be a few bytes and to gigabytes in length.

How is this done the easiest that does not take up too much memory?

回答1:

Something like this:

public static void CopyText(TextReader input, TextWriter output)
{
    char[] buffer = new char[8192];
    int length;
    while ((length = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, length);
    }
}

Note that this is very similar to what you'd write to copy the contents of one stream to another - this just happens to be text data instead of binary data.