【问题标题】:How to write contents of one file to another file?如何将一个文件的内容写入另一个文件?
【发布时间】:2011-04-24 06:54:37
【问题描述】:

我需要使用 File.OpenRead 和 File.OpenWrite 方法将文件的内容写入另一个文件。我不知道该怎么做。

如何修改以下代码以适合我。

using (FileStream stream = File.OpenRead("C:\\file1.txt"))
using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
{
       BinaryReader reader = new BinaryReader(stream);
       BinaryWriter writer = new BinaryWriter(writeStream);
       writer.Write(reader.ReadBytes(stream.Length));
}

【问题讨论】:

  • 您发布的代码有什么问题?你得到什么错误?
  • 我对是否应该一次性读取所有字节感到困惑?除了 stream.length 很长而 reader.ReadBytes 期望 int 之外,还有什么含义。
  • 您的问题是关键——您是否应该一口气读取所有字节?这意味着在调用这段代码时您希望进程使用多少内存(当然,基于文件大小)。一口气读完可能会消耗大量内存。其他答案显示了如何将其分成 1K 或 4K 位。如果将其分块,请注意它可能会导致性能下降。这些是你的取舍。分析您的情况并选择最适合您的要求。

标签: c# .net


【解决方案1】:
    using (FileStream stream = File.OpenRead("C:\\file1.txt"))
    using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
    {
        BinaryReader reader = new BinaryReader(stream);
        BinaryWriter writer = new BinaryWriter(writeStream);

        // create a buffer to hold the bytes 
        byte[] buffer = new Byte[1024];
        int bytesRead;

        // while the read method returns bytes
        // keep writing them to the output stream
        while ((bytesRead =
                stream.Read(buffer, 0, 1024)) > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
        }
    }

只是想知道为什么不使用这个:

File.Copy("C:\\file1.txt", "D:\\file2.txt");

【讨论】:

  • 是否需要 BinaryReader 和 BinaryWriter 语句?
  • 当然可以用“var”替换它们
  • 你能告诉我这两个语句的用途吗?换句话说,如果没有这两个语句会发生什么?
  • File.Copy 就是这么简单!谢谢!
  • 我可以看到您希望在覆盖一组文件之前成功打开 FileStreams 的场景。这样,如果您要使用 File.Copy,您的 5 个文件中的 2 个不会被覆盖。为此,您需要首先在所有文件上打开 FileStream,然后使用您已经打开的文件流与二进制写入器和读取器一起覆盖它们
【解决方案2】:

你应该使用File.Copy,除非你想追加到第二个文件。

如果你想追加,你仍然可以使用 File 类。

string content = File.ReadAllText("C:\\file1.txt");
File.AppendAllText("D:\\file2.txt",content);

这适用于较小的文件,因为整个文件加载到内存中。

【讨论】:

  • 简单,适合小文件。显然,您不想将其用于大文件,因为您会将整个文件内容加载到内存中。
【解决方案3】:

尝试以下方法:

using (FileStream input = File.OpenRead(pathToInputFile),
    output = File.OpenWrite(pathToOutputFile))
{
    int read = -1;
    byte[] buffer = new byte[4096];
    while (read != 0)
    {
        read = input.Read(buffer, 0, buffer.Length);
        output.Write(buffer, 0, read);
    }
}

请注意,这有点“骨架”,您应该根据应用程序的需要进行修改。

【讨论】:

  • 你为什么说,我应该根据我的应用程序要求更改它?你的意思是说我需要决定块大小(在你的情况下是 4mb)?我们真的应该分块读取字节还是可以一口气完成?
  • @Sumee 我想一口气读完它取决于你的文件大小,如果你有一个非常大的文件,也许读取所有文件可能对你的缓冲区来说太大了? (我不知道会发生什么,除此之外我怀疑您可能无法按预期获得所有文本)
  • @Wes Price - 抱歉我的意思是 4k
  • @Summe:是的,将文件路径和缓冲区长度更改为所需的值。正如 onaclov2000 提到的那样,增量阅读可能会让您受益,如果您有一个大文件,那么可能会出现一些症状,这种方法可以帮助您缓解。
  • @Eugene:我相信偏移量将用于指定任一文件中当前位置的偏移量,但是,我们不需要任何进一步的偏移量,因为我们在任一文件中的位置是由我们上次读取或写入的字节数决定。
【解决方案4】:

我们需要FileStream吗?因为您可以使用简单的文件类非常轻松地做到这一点;

using System.IO;
string FileContent = File.ReadAllText(FilePathWhoseTextYouWantToCopy);
File.WriteAllText(FilePathToWhomYouWantToPasteTheText,FileContent);

【讨论】:

    【解决方案5】:
    using (var inputStream = File.OpenRead(@"C:\file1.txt"))
    {
        using (var outputStream = File.OpenWrite(@"D:\file2.txt"))
        {
            int bufferLength = 128;
            byte[] buffer = new byte[bufferLength];
            int bytesRead = 0;
    
            do
            {
                bytesRead = inputStream.Read(buffer, 0, bufferLength);
                outputStream.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);
        }
    }
    

    【讨论】:

    • 这个会追加还是覆盖?
    【解决方案6】:

    使用FileStream 类,来自System.IO

    [ComVisibleAttribute(true)]
    public class FileStream : Stream
    

    【讨论】:

    • 我的代码示例使用文件流。我应该如何修改此代码才能工作?
    【解决方案7】:

    您是否检查过阅读器正在阅读所有数据? This MSDN page 有一个例子,检查所有数据是否被读取:

        byte[] verifyArray = binReader.ReadBytes(arrayLength);
        if(verifyArray.Length != arrayLength)
        {
            Console.WriteLine("Error reading the data.");
            return;
        }
    

    另一种选择是您可能需要Flush 输出缓冲区:

    writer.Flush();
    

    【讨论】:

      【解决方案8】:

      如果你不喜欢使用 File 的 Read/Write 功能,你可以尝试使用 Copy 功能

      Easiest will be : 
      
            File.Copy(source_file_name, destination_file_name, true)
      

      true--> 用于覆盖现有文件,如果没有“true”,它将创建一个新文件。但是如果文件已经存在,它将抛出没有“true”参数的异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多