Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize my BinaryWriter?

Tags:

c#

ftp

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

like image 323
Camal Avatar asked Aug 08 '26 20:08

Camal


1 Answers

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

like image 59
Jon Skeet Avatar answered Aug 10 '26 11:08

Jon Skeet