编辑:显然,我的建议是错误的/无效的/无论如何......请使用其中一个毫无疑问已经高度重构到无法实现额外性能的其他建议(否则,这意味着他们是和我的一样无效)
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\mydata.dat"))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\mynewdata.dat"))
{
byte[] bytes = new byte[1024];
int count = 0;
while((count = sr.BaseStream.Read(bytes, 0, bytes.Length)) > 0){
sw.BaseStream.Write(bytes, 0, count);
}
}
}
读取所有字节
byte[] bytes = null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\mydata.dat"))
{
bytes = new byte[sr.BaseStream.Length];
int index = 0;
int count = 0;
while((count = sr.BaseStream.Read(bytes, index, 1024)) > 0){
index += count;
}
}
读取所有字节/写入所有字节(来自 svick 的回答):
byte[] bytes = File.ReadAllBytes(@"C:\mydata.dat");
File.WriteAllBytes(@"C:\mynewdata.dat", bytes);
其他答案的性能测试:
刚刚在我的答案(StreamReader)(上面的第一部分,文件复制)和 svick 的答案(FileStream/MemoryStream)(第一个)之间进行了快速测试。测试是代码的 1000 次迭代,以下是 4 次测试的结果(结果以整秒为单位,所有实际结果都略高于这些值):
My Code | svick code
--------------------
9 | 12
9 | 14
8 | 13
8 | 14
如您所见,至少在我的测试中,我的代码表现得更好。我可能要注意的一件事是我没有读取字符流,实际上我正在访问提供字节流的 BaseStream。也许 svick 的回答很慢,因为他使用两个流进行读取,然后使用两个流进行写入。当然,svick 的回答可以做很多优化来提高性能(他还提供了简单文件复制的替代方案)
使用第三个选项进行测试 (ReadAllBytes/WriteAllBytes)
My Code | svick code | 3rd
----------------------------
8 | 14 | 7
9 | 18 | 9
9 | 17 | 8
9 | 17 | 9
注意:以毫秒为单位,第三个选项总是更好