Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create copy of file using StreamReader and StreamWriter

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();
        }
    }
}
like image 207
claraichu Avatar asked Aug 05 '15 01:08

claraichu


People also ask

Will StreamWriter create a file?

The first step to creating a new text file is the instantiation of a StreamWriter object. The most basic constructor for StreamWriter accepts a single parameter containing the path of the file to work with. If the file does not exist, it will be created. If it does exist, the old file will be overwritten.

What is StreamReader and StreamWriter?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.

How does a StreamReader differ from a StreamWriter?

A StreamReader is used whenever data is required to be read from a file. A Streamwriter is used whenever data needs to be written to a file.


1 Answers

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

like image 61
dbones Avatar answered Nov 14 '22 22:11

dbones