输出流写得更多,读取 - C#

时间:2013-12-15 07:16:11

标签: c# .net stream filestream

我有一个脑死亡的时刻,茫然地盯着这段代码片段10分钟...有人可以告诉我为什么输出文件(test2.txt)包含更多文本,它正在阅读的文件来自(test.txt)??

这是代码:

FileStream inputStream = new FileStream(@"C:\Temp\test.txt", FileMode.Open);
FileStream outputStream = new FileStream(@"C:\Temp\test2.txt", FileMode.OpenOrCreate);
byte[] buffer = new byte[1024];

Console.WriteLine(new FileInfo(@"C:\Temp\test.txt").Length + "\n");

while (inputStream.Read(buffer, 0, buffer.Length) > 0)
{
      Console.WriteLine("bufferlength " + buffer.Where(x => x != 0).ToArray().Length);
      Console.WriteLine(new FileInfo(@"C:\Temp\test2.txt").Length);
      outputStream.Write(buffer, 0, buffer.Length);
      outputStream.Flush();
      Console.ReadKey();
}

Console.WriteLine("\n" + inputStream.Length);
Console.WriteLine(outputStream.Length);
Console.Read();

谢谢你们

1 个答案:

答案 0 :(得分:1)

这是因为您创建了一个大小为1024的字节数组。因此,即使inputStream长度小于1024,它仍会将1024字节写入您的文件。

<罢工>

您应该使用inputStream大小初始化它,以便只将有限的字节写入您的文件:

byte[] buffer = new byte[inputStream.Length];

<击>

<强>更新

Silvermind在评论中指出正确,让缓冲区数组大小为1024.而不是use byte size returned by Read方法写入您的文件,以便只将字节读取写入文件:

int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
    Console.WriteLine("bufferlength " + buffer.Where(x => x != 0)
                                                  .ToArray().Length);
    Console.WriteLine(new FileInfo(@"D:\Temp\test2.txt").Length);
    outputStream.Write(buffer, 0, bytesRead); <- HERE
    outputStream.Flush();
}

在旁注中,您应该在使用后dispose FileStream's以避免任何内存泄漏。您可以wrap them in using block在使用后自动为您处理它。

using (FileStream inputStream = new FileStream(@"C:\Temp\test.txt",
                                                 FileMode.Open))
{
    using (FileStream outputStream = new FileStream(@"C:\Temp\test2.txt",
                                                      FileMode.OpenOrCreate))
    {
        byte[] buffer = new byte[inputStream.Length];
        Console.WriteLine(new FileInfo(@"C:\Temp\test.txt").Length + "\n");
        int bytesRead;
        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            Console.WriteLine("bufferlength " + buffer.Where(x => x != 0)
                                                  .ToArray().Length);
            Console.WriteLine(new FileInfo(@"D:\Temp\test2.txt").Length);
            outputStream.Write(buffer, 0, bytesRead); <- HERE
            outputStream.Flush();
         }
        Console.WriteLine("\n" + inputStream.Length);
        Console.WriteLine(outputStream.Length);
    }
}