如何优化我的BinaryWriter?

Cam*_*mal 2 c# ftp

我目前正在通过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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我对这段代码的问题是:

  1. 它工作得很慢,有优化方法吗?
  2. 我要求EOF(EndOfFile)的方式似乎很奇怪,还有另一种优雅的选择吗?

非常感谢:D

Jon*_*eet 10

为什么你要使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用8K缓冲区,但你可以明显改变它.哦,它重用缓冲区,而不是每次都创建一个新的字节数组,这是你的代码将要做的:)(你不需要分配字节数组开始 - 你可以readBytes在打电话给bReader.ReadBytes.)