I\'m currently working with tcp/ip suite. I\'m writing a program to encrypt files at sender\'s end and decrypt at receiver\'s side. I came across this exception while initia
To determine the length of a stream, you need to be able to read to the end of it (i.e. you Seek
to the end). Since this is a network stream, you can't just do this, hence the error you're experiencing. You will need to just keep reading bytes into a buffer until the stream ends, and only then will you know the length of your payload. Here's a suggestion:
if (client.Connected)
{
NetworkStream binarystream = client.GetStream();
Stream file = File.OpenWrite(saveFileDialog1.FileName);
byte[] buffer = new byte[10000];
int bytesRead;
while (binarystream.DataAvailable)
{
bytesRead = binarystream.Read(buffer, 0, buffer.Length);
file.Write(buffer, 0, bytesRead);
}
file.Close();
binarystream.Close();
}
Note that I would also recommend adding using
statements for each of your stream instantiations, as this guarantees that the streams will be closed properly even if an exception is thrown while reading/writing. You could then remove the explicit calls to Close
.