我该如何从任何文件中读取原始字节数组,并将该字节数组写入新文件中?
(编辑说明:请注意,问题已更改;最初未提及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 应用程序中。
byte[]
不一定是一个好主意;对于大文件来说,这可能会非常昂贵。 - Marc Gravell