加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – FileStream很慢吗?

发布时间:2020-12-16 00:19:05 所属栏目:百科 来源:网络整理
导读:我试图将一个5 GB的ISO文件复制到一个具有29 GB可用空间的32 GB闪存驱动器上. Windows 7拒绝让我将文件拖放到闪存驱动器上,报告文件对于目标文件系统来说太大了. 我最终了解到这是因为驱动器被格式化为FAT32而不是NTFS,但是在我编写此例程以复制文件之前: p
我试图将一个5 GB的ISO文件复制到一个具有29 GB可用空间的32 GB闪存驱动器上.

Windows 7拒绝让我将文件拖放到闪存驱动器上,报告文件对于目标文件系统来说太大了.

我最终了解到这是因为驱动器被格式化为FAT32而不是NTFS,但是在我编写此例程以复制文件之前:

private void copyFile(string from,string to) {
  bool ok = true;
  using (StreamReader sr = new StreamReader(from,true)) {
    using (StreamWriter sw = new StreamWriter(to,false,sr.CurrentEncoding)) {
      int FOUR_K = 4048;
      char[] buf = new char[FOUR_K];
      try {
        while (-1 < sr.Peek()) {
          int len = sr.Read(buf,FOUR_K);
          sw.Write(buf,len);
          sw.Flush();
        }
      } 
      catch (Exception err) {
        ok = false;
        throw err;
      }
    }
  }
  if (ok) {
    Console.WriteLine("Done!");
  }
}

我让它运行了大约一个小时,文件大小只有270 MB.

这是怎么回事?

我的代码中有什么导致我的文件花了这么长时间?

这是我选择的FOUR_K变量大小吗?

[UPDATE]

我有两个ISO文件:Win8-32bit在~3 GB,Win8-64bit-Developer在~5 GB.使用拖放功能,Windows资源管理器在大约三分钟内将3 GB文件复制到我的32 GB闪存驱动器中.

使用Marc Gravell的技术,我又一次去了:

[STAThread]
static void Main(string[] args) {
  using (OpenFileDialog dlg = new OpenFileDialog()) {
    dlg.Title = "Select File";
    if (dlg.ShowDialog() == DialogResult.OK) {
      using (FolderBrowserDialog fdg = new FolderBrowserDialog()) {
        fdg.Description = "Select Destination";
        if (fdg.ShowDialog() == DialogResult.OK) {
          DateTime start = DateTime.Now;
          Console.WriteLine("Started at {0:g}.nWorking...",start);
          using (FileStream fin = File.Open(dlg.FileName,FileMode.Open)) {
            using (FileStream fout = new FileStream(Path.Combine(fdg.SelectedPath,dlg.SafeFileName),FileMode.Create)) {
              try {
                fin.CopyTo(fout);
              } catch (Exception err) {
                Console.WriteLine("An Error Occurred:");
                Console.WriteLine(err.Message);
              }
            }
          }
          DateTime end = DateTime.Now;
          TimeSpan span = (end - start);
          Console.WriteLine("Process Ended at {0}.nThe total minutes passed = {1}.",end,span.TotalMinutes);
          Console.WriteLine("Press Any Key.");
          Console.ReadKey();
        }
      }
    }
  }
}

使用上面的FileStream实例,程序运行了大约8个小时,正好复制了4,194,300 KB,然后抛出了Out Of Memory Exception.

解决方法

我不知道性能问题(听起来很奇怪),但是没有理由在这里使用StreamReader / StreamWriter,因为你可以只在二进制级别进行复制.实际上,ISO映像不是文本,因此将其读入char数据很可能会破坏事物.有关信息,即使您不想使用 File.Copy,您只需要:

using(var inFile = File.OpenRead(source))
using(var outFile = File.Create(destination))
{
    inFile.CopyTo(outFile);
}

要在一小时内获得270k,你需要努力(除非IO基本上死了);我的猜测是它在某处发生了错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读