FileStream无法正常工作

时间:2014-06-22 07:40:39

标签: c#

我正在尝试使用ReadByte方法读/写文件。代码正在运行,但我注意到它们在进程后无法使用。我无法打开它们。我的图像没有显示。我一次又一次地做错了。

 if (openFileDialog1.ShowDialog() == DialogResult.OK) {
     if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
          FileStream fsRead = 
              new FileStream(openFileDialog1.FileName, FileMode.Open);
          FileStream fswrite = 
              new FileStream(saveFileDialog1.FileName, FileMode.Create);

         if (fsRead.Position != fsRead.Length) {
             byte b = (byte)fsRead.ReadByte();
             fswrite.WriteByte(b);
         }      
     }
}

2 个答案:

答案 0 :(得分:4)

你只读一个字节 - 我怀疑你意味着写一个while循环而不是if语句:

while (fsRead.Position != fsRead.Length) {
   byte b = (byte)fsRead.ReadByte();
   fswrite.WriteByte(b);
}

然而,这仍然不是很有效率。通常,最好一次读取和写入块,使用“我不能再读取”来指示文件的结尾:

byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fsRead.Read(buffer, 0, buffer.Length)) > 0) {
    fswrite.Write(buffer, 0, bytesRead);
}

但是,您自己并不需要这样做,因为您可以使用Stream.CopyTo为您执行此操作:

fsRead.CopyTo(fswrite);

请注意,您还应该为流使用using语句,以便在语句结束时自动关闭它们。我还使用File.OpenWriteFile.OpenRead而不是调用FileStream构造函数,只使用Stream变量:

using (Stream read = File.OpenRead(openFileDialog1.FileName),
             write = File.OpenWrite(saveFileDialog1.FileName))
{
    read.CopyTo(write);
}

或者当然只使用File.Copy

答案 1 :(得分:0)

您需要在使用后关闭文件,它们将被锁定,直到该文件。

最佳做法是使用using (var fs = new FileStream(...) { ... }构造 - 在这种情况下,文件流和底层文件将在使用范围完成后关闭。

所以它应该是这样的:

if (openFileDialog1.ShowDialog() == DialogResult.OK) {
    if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
        using (FileStream fsRead = new FileStream(openFileDialog1.FileName, FileMode.Open))
        using (FileStream fswrite = new FileStream(saveFileDialog1.FileName, FileMode.Create)) {
            // your logic here
            if (fsRead.Position != fsRead.Length) {
               byte b = (byte)fsRead.ReadByte();
               fswrite.WriteByte(b);
            }
        }
    }