views:

67

answers:

1

I'm trying to serialize a string with some escape characters (\0). But when I deserialise it throws an exception.

//XML serialization

    private static void M1()
        {
            string str = "\0AC";

           StringWriter sw = new StringWriter();
            XmlSerializer serializer = new XmlSerializer(typeof(String));
            serializer.Serialize(sw, str);
            System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString());
            StringReader sr = new StringReader(sw.ToString());
            String s2 = (String)serializer.Deserialize(sr);

            System.Console.WriteLine("String decoded from XML = \n {0}", s2);
        }

//Using Binary serialization

    void BinaryFormat1()
     {
         IFormatter bf = new BinaryFormatter();
         string str = "\0MyName";
         FileStream fs = new FileStream("SerilizedString.Data", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
         bf.Serialize(fs, str);
         fs.Close();
         fs = new FileStream("SerilizedString.Data", FileMode.Open, FileAccess.Read, FileShare.None);
         string data = (string)bf.Deserialize(fs);
         fs.Close();
         Console.WriteLine("data : " + data.ToString());
     }
+3  A: 

I'd expect SOAP to have the same problem, to be honest. It's the issue of not being able to represent every Unicode string in "standard" XML.

That leaves binary serialization, which:

  • Will only work with .NET (so is bad for interoperability)
  • Isn't human readable (or easily translated into a human readable form if you run into problems)
  • Is hard to work with in terms of versioning

Personally I prefer custom serialization options such as Thrift or Protocol Buffers, but as the author of a Protocol Buffers port to C#, I'm biased :)

Jon Skeet
When i tried to use binary serialization application doesnt throw exception, but it doesnt show any output
@starz26: Using your exact code, it shows the output fine for me. Try running it *from a console*. If you're running it from something like Visual Studio, the "\0" may be confusing the Windows widgets, which often treat that as "end of string".
Jon Skeet
There is another application that takes input from my application.In that case my deserilaized output is the input to another application.So does it mean my output data will go to another application. yes Im using the visual studio to see this working
@starz: So what does your other application require? Or can you change that to do whatever you want?
Jon Skeet
Amen on versioning.
micahtan