简体   繁体   中英

How to optimize my BinaryWriter?

i am currently working at a program that transfer files via FTP. I send the files in binary because with ASCII I can´t send special characters.

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 ?

Thanks alot :D

Why are you using BinaryReader and BinaryWriter at all? 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. 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 .)

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.

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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