title: Send / receive file over TCP
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3609280/tcpclient-send-data-and-receive-data-over-network">TcpClient send data and receive data over network</a><br>
    <a href="https://stackoverflow.com/questions/8027664/loop-until-tcpclient-response-fully-read">Loop until TcpClient response fully read</a>  </p>
  </blockquote>
  
  
  
  <p>I am trying to send a file from a server to a client over TCP.</p>
  
  <p>Server-side code, sending file:</p>
  
  <pre><code>NetworkStream netStream = client.GetStream();
  FileStream fs = new FileStream("usb.exe",FileMode.Open, FileAccess.Read);
  byte[] data = new byte[fs.Length];
  fs.Read(data,0, data.Length);
  fs.Flush();
  fs.Close();
  
  netStream.Write(data, 0, data.Length);
  netStream.Flush();
  </code></pre>
  
  <p>Client-side code, receive file:</p>
  
  <pre><code>FileStream str = new FileStream("usb.exe", FileMode.Create, FileAccess.Write);
  byte[] data = new byte[1024];
  
  while ((dataCitit = netStream.Read(data,0, data.Length)) &gt; 0)
      {
           Thread.Sleep(25);
           Application.DoEvents();
  
           str.Write(data, 0, dataCitit);
           totalbytes += dataCitit;                      
      }
  str.Close();
  </code></pre>
  
  <p>Can someone point where I am getting it wrong ? </p>
  
  <p>The file has 1036 kb, and it sends only 1032 kb and then gets stuck it won't get out the while loop on the client-side. </p>
  
  <p>Also if I close the server and open it really quick it sends the last bytes and the files sends completely. (this file opens perfectly)</p>
  
  <p>I think it`s a problem on the server side not sending all the bytes but why and where...</p>