Link to home
Start Free TrialLog in
Avatar of pointeman
pointemanFlag for United States of America

asked on

TCP BinaryFormatter Deserialize To File?

I always 'write' an emty file, not sure exacty where I went wrong, help!

[Sending]
tcpClient = new TcpClient();
tcpClient.Connect(IPAddress.Parse("192.168.1.7"), 5000);
NetworkStream ns = tcpClient.GetStream();
IFormatter bf = new BinaryFormatter();
bf.Serialize(ns,"test.txt");
tcpClient.Close();

[Receiving]
listener = new TcpListener(IPAddress.Any, 5000);
listener.Start();
                       
while ((client = listener.AcceptTcpClient()) != null)
{
     NetworkStream ns = client.GetStream();
     object obj = null;

     if (ns.DataAvailable)
     {
           try
           {
                  IFormatter bf = new BinaryFormatter();
                  obj = bf.Deserialize(ns);
           }
           finally
           {                            
                  StreamWriter sw = new StreamWriter(new FileStream("test.txt", FileMode.Create, FileAccess.Write, FileShare.Read));
                  sw.WriteLine(obj.ToString());
           }
     }
Avatar of lazyberezovsky
lazyberezovsky
Flag of Belarus image

You are serializing string "test.txt", not content of test.txt file:
bf.Serialize(ns,"test.txt");
Avatar of pointeman

ASKER

I haven't tried this yet, but I understand your point...

FileStream fs = new FileStream("test.txt", FileMode.Open) ;
bf.Serialize(ns, fs);
ASKER CERTIFIED SOLUTION
Avatar of lazyberezovsky
lazyberezovsky
Flag of Belarus image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I read other posts on the Internet where people experienced problems sending both text files and image files. I thought serialization would enable sending any file type via TCP?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Okay, understood. I also read about poor serialization performance too. Anyway, I used your code and could not receive the data on the client and write to file. Always blank file... Help
Q. How do you receive the file and write it to harddrive?
Thanks for helping me understand...