How to create copy of file using StreamReader and StreamWriter

claraichu picture claraichu · Aug 5, 2015 · Viewed 22.4k times · Source

I need to use StreamReader to read a .txt file on a console application, then create a new file or backup with a different name but same content. The problem is i cant figure out how to use the content from the first file to place into the new one. (This is for a school thing and im new to C#)

using System;
using System.IO;
namespace UserListCopier
{
    class Program
    {
        static void Main()
        {
            string fineName = "zombieList.txt";

            StreamReader reader = new StreamReader(fineName);

            int lineNumber = 0;

            string line = reader.ReadLine();

            while (line != null) {
                lineNumber++;
                Console.WriteLine("Line {0}: {1}", lineNumber, line);
                line = reader.ReadLine();
            }

            StreamWriter writetext = new StreamWriter("zombieListBackup.txt");

            writetext.Close();
            System.Console.Read();
            reader.Close();
        }
    }
}

Answer

dbones picture dbones · Dec 15, 2015

Lets consider you have opened both streams, similar @jeff's solution, but instead of ReadToEnd (not really steaming effectively), you could buffer the transfer.

_bufferSize is an int set it to a buffer size that suits you (1024, 4096 whatever)

private void CopyStream(Stream src, Stream dest)
{
    var buffer = new byte[_bufferSize];
    int len;
    while ((len = src.Read(buffer, 0, buffer.Length)) > 0)
    {
        dest.Write(buffer, 0, len);
    }
}

here is a gist, containing a class which calculates the speed of transfer https://gist.github.com/dbones/9298655#file-streamcopy-cs-L36