isaksson

isaksson

  • NA
  • 1
  • 0

serialization of objects between programs

Jun 14 2004 10:02 AM
Hi! I am trying to send objects between server and client programs. To do so I have created a simple serialized test object to send between the programs. For each of the programs I have made an assembly with a strong name. All code is written in C#. It feels like this shouldn't be such a big problem but I have been stuck with it for some time now. The problem I am having is that both sending the serialized object over the network and writing it to a file goes wrong. Exceptions is thrown saying that the casting I try to do is wrong or that the object I recieved wasn't instantiated. It's the same problem both when sending the object over network and when writing it to file. When I write the object to a file in one program and then read it in the same program everything works fine, so it seems like the serialization works. I don't know if it's the assemblys that is causing problem or if I have done something else wrong. If anyone have an idea please post, have been trying to solve this problem for days now. Here is the code: /****************************************************/ // Data object to be serialized /****************************************************/ [Serializable] public class Data { public String name; public Data() { name = "MyName"; } public String getName() { return name; } } /****************************************************/ // End Data object /****************************************************/ /****************************************************/ // Client /****************************************************/ Stream streamRead = new FileStream("test.txt",FileMode.Open, FileAccess.Read, FileShare.Read); try { IFormatter formatter = new BinaryFormatter(); Data d; //this cause InvalidCastException, don't know why. //d = (Data) formatter.Deserialize(streamRead); d = formatter.Deserialize(streamRead) as Data; Console.Write("data recieved: " + d.getName()); //this cause NullReferenceException } catch(System.NullReferenceException e) { Console.Write("\nException meddelande" + e.Message); } catch(System.InvalidCastException e) { Console.Write("\nException meddelande" + e.Message); } } streamRead.Close(); /****************************************************/ // End Client /****************************************************/ /****************************************************/ // Server /****************************************************/ Stream streamWrite = new FileStream("test.txt", FileMode.Create, FileAccess.Write, FileShare.None); Data d = new Data(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(streamWrite, d); streamWrite.Close(); /****************************************************/ // End Server /****************************************************/ Grateful for any help //Sitrom