简体   繁体   English

如何优化我的BinaryWriter?

[英]How to optimize my BinaryWriter?

i am currently working at a program that transfer files via FTP. 我目前正在通过FTP传输文件的程序。 I send the files in binary because with ASCII I can´t send special characters. 我发送二进制文件,因为使用ASCII我不能发送特殊字符。

Here is my currently code : 这是我目前的代码:

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

My Problems with this code are : 我对这段代码的问题是:

  1. It works really slow, is there a way to optimize ? 它工作得很慢,有优化方法吗?
  2. The way i ask for EOF(EndOfFile) seems to be very strange, is there another elegance option ? 我要求EOF(EndOfFile)的方式似乎很奇怪,还有另一种优雅的选择吗?

Thanks alot :D 非常感谢:D

Why are you using BinaryReader and BinaryWriter at all? 为什么你要使用BinaryReader和BinaryWriter? Why are you repeatedly asking for the length? 你为什么一再要求长度? Here's a method I've posted a bunch of times now: 这是我现在发布了很多次的方法:

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

That uses an 8K buffer, but you can change that obviously. 它使用8K缓冲区,但你可以明显改变它。 Oh, and it reuses the buffer rather than creating a new byte array every time, which is what your code will do :) (You don't need to allocate the byte array to start with - you could have declared readBytes at the point of the call to bReader.ReadBytes .) 哦,它重用缓冲区,而不是每次都创建一个新的字节数组,这是你的代码将要做的:)(你不需要分配字节数组开始 - 你可能已经声明了readBytesbReader.ReadBytes的调用。)

I think your performance issues are coming from two places. 我认为你的表现问题来自两个地方。 You are calling bReader.BaseStream.Length every time through the loop and your call to bReader.ReadBytes() is allocating a new byte array every time. 您每次通过循环调用bReader.BaseStream.Length每次调用bReader.ReadBytes()都会分配一个新的字节数组。

I also don't think the BinaryReader and BinaryWriter are necessary as you aren't using their features for reading and writing types other than byte arrays, which are already supported in the underlying streams through Stream.Read() and Stream.Write() . 我也不认为BinaryReader和BinaryWriter是必要的,因为你没有使用它们的功能来读取和写入字节数组以外的类型,这些类型已经通过Stream.Read()Stream.Write()在底层流中得到支持。

I would do this as: 我会这样做:

byte [] buffer = new byte[1024];
int bytesRead;
while ( (bytesRead = srcStream.Read(buffer, 0, buffer.Length)) != 0 )
{
    dstStream.Write(buffer, 0, bytesRead);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM