使用以下代码,我可以将PrinterSettings序列化/反序列化为文件。 我想问一下是否有一种方法可以将其序列化为字符串或字节数组或类似的东西,以便将其直接保存到数据库中。
谢谢!
PrinterSettings prtSettings = new PrinterSettings();
prtSettings.PrintFileName = "does not matter, unused if PrintToFile == false";
//serialise
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(prtSettings.GetType());
using (System.IO.TextWriter txtWriter = new StreamWriter(@"c:\temp\printerSettings.xml"))
{
xmlSerializer.Serialize(txtWriter,prtSettings);
}
//deserialise
using (FileStream fileStream = new FileStream(@"c:\temp\printerSettings.xml", FileMode.Open))
{
object obj = xmlSerializer.Deserialize(fileStream);
prtSettings = (PrinterSettings)obj;
}
答案 0 :(得分:3)
string printerSettingText = "";
XmlSerializer xser = new XmlSerializer(typeof(PrinterSettings));
using (StringWriter sw = new StringWriter())
{
xser.Serialize(sw, prtSettings);
printerSettingText = sw.ToString();
}
对象的反序列化很简单
string dataToDeserialize = GetYourDataFromDb();
xser = new XmlSerializer(typeof(PrinterSettings));
using (StringReader sr = new StringReader(dataToDeserialize))
{
PrinterSettings prn = (PrinterSettings)xser.Deserialize(sr);
Console.WriteLine(prn.PrintFileName);
}