Click here to Skip to main content
15,916,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
im trying to send file over TCP using C# while receiving file i found that it's 0 KB how to Fix it ? here's the Code //server

C#
TcpListener list = new TcpListener(localAddr, port);
           list.Start();
           TcpClient client  = list.AcceptTcpClient();//accepting connection with client when send button is clicked there .. !
           StreamReader s = new StreamReader(client.GetStream());
           Stream st = client.GetStream();
           rd = s.ReadLine();
           //FileStream fileStream = new FileStream(textBox1.Text + "\\" + rd.Substring(0, rd.LastIndexOf('.')), FileMode.Create, FileAccess.Write, FileShare.ReadWrite);//new file stream

           FileStream fileStream = new FileStream(folderBrowserDialog1.SelectedPath , FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);//new file stream

           int byteSize = 0;
           byte[] b1 = new byte[2048];



           while ((byteSize = st.Read(b1, 0, b1.Length)) > 0)//if stream read any thing that mean the file didn't finish yet !
           {
             fileStream.Write(b1, 0, byteSize);//write data in file till it finishes


           }
Posted

1 solution

Hi there.
I have been troubling with this really really long time, trying to find an answer. Using StreamReader may be a good idea, but I did the transfer by using async method callbacks, and using AsyncResult. Then sending only the plain bytes of the file. However, the next problem I encountered was checking when the file data ends. This can be done by putting a string keyword as bbyte at the end or some unique sequence of bytes. You then just cut it, and you have bytes of the file, wich are later on written to file.

The work with the arrays is quite uncomfortable, however, and the best way to make internet apps is to use WPF or something that is done to handle this. The TCP is quite good to make for example a chat, or I did LAN card game with it, because all I had to send was ID of card, and update the health.

If you need some help, add me at skype, username: vojtech.dusny, we can talk about it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900