I do serialization by example

using System.Runtime.Serialization.Formatters.Binary; using System.IO; [Serializable] public class UserPrefs { public string WindowColor; public int FontSize; } static class Program { [STAThread] static void Main() { UserPrefs userData = new UserPrefs(); userData.WindowColor = "Yellow"; userData.FontSize = 50; BinaryFormatter binFormat = new BinaryFormatter(); // Сохранить объект в локальном файле. using (Stream fStream = new FileStream("user.xml", FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, userData); } } } 

The file is created but as the xml file it does not open it writes it cannot display the XML page. Tell me what the error is.

  • file header contains <?xml version="1.0" encoding="UTF-8"?> ? attach the xml to the question - Senior Pomidor
  • Jayaya: RDS, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null RDS.UserPrefs WindowColorFontSize Yellow2 - polsok
  • What do you want to get? If XML then you need another serializer. - Ev_Hyper
  • give an example xml serialization - polsok
  • 2
    I give: metanit.com/sharp/tutorial/6.4.php But is it really difficult to drive a search into the search yourself? - Ev_Hyper

1 answer 1

What you find is binary serialization, not serialization in XML.

It is necessary so:

 UserPrefs userData = new UserPrefs(); userData.WindowColor = "Yellow"; userData.FontSize = 50; //var xml = JsonConvert.SerializeObject(userData); XmlSerializer seri = new XmlSerializer(typeof(UserPrefs)); // тут вам скорее всего нужен другой тип stream'с using (var s = new MemoryStream()) { seri.Serialize(s, userData); // всё, сериализация окончена // перегоним в строку для контроля s.Seek(0, SeekOrigin.Begin); var text = new StreamReader(s).ReadToEnd(); } 

The text variable will have the following:

 <?xml version="1.0"?> <UserPrefs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <WindowColor>Yellow</WindowColor> <FontSize>50</FontSize> </UserPrefs> 

If you need to write to a file, instead of a MemoryStream , but take FileStream right away, etc.

 using (var s = File.Create(@"user.xml")) { seri.Serialize(s, userData); } 
  • And why MemoryStream, but not StringWriter? - Pavel Mayorov
  • @PavelMayorov: I meant any Stream . Most likely, the TS needs a FileStream . - VladD
  • I have written everywhere so far through the MemoryStream. I think through StringWriter perhaps better ... - nick_n_a
  • @nick_n_a: MemoryStream is just for an example here, most likely the TS need a FileStream or NetworkStream. - VladD