Search code examples
.netfileremoting

.NET Remoting : Read Large File


I have a .NET Remoting application. Currently the application has functionality in which Remoting Server is required to fetch the file and send it to client as byte array. As the whole byte array is going to client at once, if the file size is big, then there is problem.

So I am thinking of implementing partial reading of the file,

like

public byte[] ReadPartialFile(string fileName, int offset, int bufferSize)
{
   //use FileStream and BinaryReader to read the required (depends of offset and buffer) bytes and send them back...
}

But I am afraid that if file is large and buffer size small, the FileStream and related objects would be created and disposed of N number of times, which can adversely impact the application....

I also don't want to spike application's (client & server) memory consumption...

Anyone got better ideas...


Solution

  • Since Stream is MarshalBy Ref you can pass a stream from client to the server

    public unsafe void ReadFileFromSensor(Stream destination)
    {
         //server writes to stream
         destination.Write(buffer, 0, buffer.Length);
    }
    

    The other way round will not work. If you read from a stream over remoting, the passed array will be serialized and will therefore not be filled.

    In this case we have defined an extension method for stream without the need to pass an array

    public static byte[] Read(this Stream stream, int nBytesToRead, out  int nBytesRead)
    {
            byte[] buffer = new byte[nBytesToRead];
            nBytesRead = stream.Read(buffer,0,nBytesToRead);
            return buffer;
    }
    

    We use this method to communicate over local Ethernet. There it is not a problem for the server to access the stream on the client. But it may be a problem in other scenarios if the server have to connect back to the client.