Csharp/C#教程:C# – 如何读写二进制文件?分享


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应用。

上述就是C#学习教程:C# – 如何读写二进制文件?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1005079.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐