我目前正在研究一个通过 FTP 传输文件的程序。我以二进制形式发送文件,因为使用 ASCII 我无法发送特殊字符。
这是我目前的代码:
using(BinaryReader bReader = new BinaryReader(srcStream))
using (BinaryWriter bWriter = new BinaryWriter(destStream))
{
Byte[] readBytes = new Byte[1024];
for(int i = 0; i < bReader.BaseStream.Length; i += 1024)
{
readBytes = bReader.ReadBytes(1024);
bWriter.Write(readBytes);
}
}
我对这段代码的问题是:
- 它运行起来真的很慢,有没有办法优化?
- 我要求 EOF(EndOfFile) 的方式似乎很奇怪,还有其他优雅的选择吗?
非常感谢:D
最佳答案
您为什么要使用 BinaryReader 和 BinaryWriter?你为什么反复问长度?这是我现在已经发布了很多次的方法:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8192];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
它使用 8K 缓冲区,但您显然可以更改它。哦,它会重用缓冲区而不是每次都创建一个新的字节数组,这是您的代码将要做的:)(您不需要分配字节数组来开始 - 您可以声明 readBytes
在 bReader.ReadBytes
的调用点。)
关于c# - 如何优化我的 BinaryWriter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1270996/