tags:

views:

301

answers:

2

Hey there, 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

+5  A: 

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

Jon Skeet
First thing first, thanks Jon.But now i am very confused :D I am pretty new to working with Streams and i was thinking i can only writer with BinaryWriter in binary Mode.So Streams got Methods Read/Write, too. And agian i learned something :DBut just in case if a file has a size of "0" but i want to transfer that file too. If this working for me ?
Camal
That will work fine, yes - the first call to Read will return 0, and you'll exit the loop. BinaryReader/BinaryWriter are utility classes to read and write primitives etc over streams. Streams themselves are just binary sources and destinations for data - the other thing commonly wrapped round them are StreamReader/StreamWriter which decode/encode text.
Jon Skeet
+2  A: 

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