A
A
AnTifriZZ2015-01-18 18:23:41
.NET
AnTifriZZ, 2015-01-18 18:23:41

How to read data stream to file from NetworkStream?

Hey! please tell me how I can’t figure out the problem:
I’m trying to read a data stream to a file from a NetworkStream
every time in a while loop, it results in ioexception: {"Unable to read data from the transport connection: The remote host forcibly terminated the existing connection."}
that I am I doing it wrong?
fails when trying to read from the stream: bytesRead = clientStream.Read(data, 0, bufferSize);

//********
TcpListener listener = new TcpListener(IPAddress.Any, Properties.Settings.Default.Port);
listener.Start();
 
TcpClient client = listener.AcceptTcpClient();
 
NetworkStream clientStream = client.GetStream();
//********
 
byte[] data = new byte[bufferSize]; // Создаем массив для файла
 
string fullFilename = Properties.Settings.Default.PictureDirectory + name; // Полный путь для upload
 
using (FileStream fileStream = File.Open(fullFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
   int bytesRead = 0;
   try
   {
      do
      {
         bytesRead = clientStream.Read(data, 0, bufferSize);
         fileStream.Write(data, 0, bytesRead);
      } while (bytesRead > 0);
 
      fileStream.Close();
   }
   catch (SocketException ex)
   {
      Console.WriteLine(ex.ErrorCode);
   }
   catch (IOException ex)
   {
      Console.WriteLine(ex.Message);
   }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rasim Keita, 2015-01-21
@keyros

Try replacing "while (bytesRead > 0)" with "while (bytesRead == bufferSize)"
because
if we have a stream size of 1025 (for example) bytes, and a buffer size of 512 bytes, then at first the Read method will return 512, and in the last iteration it will return 1
here is a link to MSDN

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question