1

I am sending a file over the network using a client-server program. After reading the bytes of the file (with File.ReadAllBytes()), I set the byte array as a field of an object. Then serialize and send the object to the client, where the client should deserialize the object and get the file by using a BinaryWriter.

All the messages between client-Server are passed through serializing an object of a class called Command.

This method seems to consume a lot of memory when the file is loaded to the byte array.

Can anyone propose another mechanism where I can send the file little by little, without consuming too much memory. Is it possible to send the file's memory address and then the server pull the file little by little using the memory address on the client (using a loop)?

manas
  • 397
  • 6
  • 25

1 Answers1

2

I think the best option is to use streaming transfer. It's a native feature in wcf.

You can find help here and here.

EDIT :

You can try to read & send like this way :

  using (FileStream fs = new FileStream(@"C:\...\file.txt", FileMode.Open))
  {
    byte[] buffer = new byte[1024];
    int len;
    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
    {
      //client.Send(buffer, 0, len);
    }
  }
Cybermaxs
  • 24,378
  • 8
  • 83
  • 112
  • I am already using Sockets. this seems like requiring a complete restructuring of the code, doesn't it? @cybermaxs – manas Sep 25 '12 at 07:57
  • yes, but it will be must easier in wcf. my answer is not appropriate because I am a big fan of wcf. also check http://stackoverflow.com/questions/5659189/how-to-split-a-large-file-into-chunks-in-c – Cybermaxs Sep 25 '12 at 08:25
  • yeps thanks, it seems a good article, but still it would be impossible to implement as I am passing messages between client-server through serializing/deserializing of objects. again a restructure is necessary, right? @cybermaxs – manas Sep 25 '12 at 11:26
  • 1
    if you want to send a file, why serializing it ? you will keep a memory of your file in memory. If the file is 4GB, you will run out of memory. see my edit – Cybermaxs Sep 25 '12 at 12:00