C# - 如何读取和写入二进制文件?
-
11-09-2019 - |
题
如何从任何文件读取原始字节数组,并将该字节数组写回到新文件中?
解决方案
(编辑:请注意,问题发生了变化;它没有提到 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);
添加一个最新的答案,
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和Windows Store应用程序这将是有益的。
不隶属于 StackOverflow