如何使用StreamReader和StreamWriter创建文件副本

我需要使用StreamReader读取控制台应用程序上的.txt文件,然后创建一个具有不同名称但内容相同的新文件或备份。 问题是我无法弄清楚如何使用第一个文件中的内容放入新文件中。 (这是针对学校的事情而且是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(); } } } 

这样做会:

 using System; using System.IO; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { using (var reader = new StreamReader(@"C:\MyOriginalFile.txt")) using (var writer = new StreamWriter(@"C:\MyNewFile.txt", append: false)) { writer.Write(reader.ReadToEnd()); } Console.Read(); } } } 

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

_bufferSize是一个int,它设置为适合你的缓冲区大小(1024,4096无论如何)

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

这是一个要点,包含一个计算转移速度的类https://gist.github.com/dbones/9298655#file-streamcopy-cs-L36

对于磁盘上的文件,您只需要File.Copy(inputPath, outputPath) 。 我不确定这是否有效地流式传输内容,或者是否将其全部读入内存然后将其全部写入一次。

因此,对于大型文件,或者如果您的流不能解析为磁盘上的路径,您可以使用以下函数有效地从一个文件复制到另一个文件:

 private void copyFile(string inputPath, string outputPath) { using (var inputStream = StreamReader(inputPath)) { using (var outputStream = StreamWriter(outputPath)) { copyToOutputStream(inputStream, outputStream); } } } private void copyToOutputStream(StreamReader inputStream, StreamWriter outputStream) { string line = null; while ((line = inputStream.ReadLine()) != null) { outputStream.WriteLine(line); } outputStream.Write(inputStream.ReadToEnd()); } 

此函数一次一行地从输入流复制到输出流,直到输入流结束。 这意味着它一次只在内存中有一行(而不是整个文件),并且它可以在第一个流完成读入/生成之前开始写入磁盘。

  public static void ReadFromFile() { using(StreamReader sr =File.OpenText(@"D:\new.txt")) { string line=null; while ((line=sr.ReadLine())!= null) { // line = sr.ReadLine; using (StreamWriter sw = File.AppendText(@"D:\output.txt")) { sw.WriteLine(line); } } } }