c# - 如何优化我的 BinaryWriter?

标签 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);
        }
    }

我对这段代码的问题是:

  1. 它运行起来真的很慢,有没有办法优化?
  2. 我要求 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 缓冲区,但您显然可以更改它。哦,它会重用缓冲区而不是每次都创建一个新的字节数组,这是您的代码将要做的:)(您不需要分配字节数组来开始 - 您可以声明 readBytesbReader.ReadBytes 的调用点。)

关于c# - 如何优化我的 BinaryWriter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1270996/

相关文章:

javascript - 连接ECONNREFUSED 127.0.0.1 :21 error in node js

c# - 如何用C#从FTPS下载文件

c# - ASP.NET核心: How to get original path in error page by 404 status code

c# - 从 C# 调用 powershell 脚本时包含脚本不起作用

regex - 如何通过 ftp 连接获取字母数字大于 Linux 命令行 (bash) 中指定的文本的文件列表?

c - ftp 的数据通道如何工作?

java xml上传问题!

c# - 异步调用带有输出参数的方法

c# - 如何从分号分隔的列表<string>中删除逗号字符?

c# - WPF上下文菜单自动滚动