C# – 如何读写二进制文件?

如何从任何文件中读取原始字节数组,并将该字节数组写回新文件?

(编辑:请注意问题已更改;最初未提及byte[] ;请参阅修订版1 )

好吧, File.Copy跳跃到脑海; 但否则这听起来像一个Stream场景:

  using (Stream source = File.OpenRead(inPath)) using (Stream dest = File.Create(outPath)) { byte[] buffer = new byte[2048]; // pick size int bytesRead; while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) { dest.Write(buffer, 0, bytesRead); } } 
 byte[] data = File.ReadAllBytes(path1); File.WriteAllBytes(path2, data); 

您是否了解TextReader和TextWriter及其后代StreamReader和StreamWriter ? 我认为这些会解决你的问题,因为它们处理编码,BinaryReader不知道编码甚至文本,它只关心字节。

如何从文件中读取文本

如何将文本写入文件

这是文件IO和编码的优秀介绍。

添加最新答案,

 using (var source = File.OpenRead(inPath)) { using (var dest = File.Create(outPath)) { source.CopyTo(dest); } } 

您可以选择指定缓冲区大小

 using (var source = File.OpenRead(inPath)) { using (var dest = File.Create(outPath)) { source.CopyTo(dest, 2048); // or something bigger. } } 

或者你可以在另一个线程上执行操作,

 using (var source = File.OpenRead(inPath)) { using (var dest = File.Create(outPath)) { await source.CopyToAsync(dest); } } 

当主线程必须执行其他工作时,这将非常有用,例如WPF和Windowsapp store应用。