本文介绍了如何使用StreamReader和StreamWriter创建文件副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用StreamReader在控制台应用程序上读取.txt文件,然后创建一个新文件或使用不同名称但内容相同的备份。问题是我无法弄清楚如何使用第一个文件中的内容放入新文件。 (这是针对学校的事情,是C#的新手)

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();
        }
    }
}


推荐答案

让我们考虑一下您已经打开了两个流,类似于@jeff的解决方案,但是您可以缓冲传输。而不是ReadToEnd(并不是真正有效地蒸腾)。

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是一个将其设置为适合您的缓冲区大小的int(1024、4096任意)

_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 transferhttps://gist.github.com/dbones/9298655#file-streamcopy-cs-L36

这篇关于如何使用StreamReader和StreamWriter创建文件副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:49