Home > Net >  C # serialization and deserialization
C # serialization and deserialization

Time:03-25

Learned in front of the method, the obtained class instance serialized to a file, and deserialization continue to use,

But see serialization, will save the namespace together, in the other form is can't open this file,

Is there any way to direct the namespace name changed, or other ways?

Said the original form production DLL, and then reference to the new form

There is no only for this a few class ah,

CodePudding user response:

 using System. IO; 
Using System, Xml Serialization;

Public static class XmlTools
{
///& lt; Summary>
///the target serialized as XML format file, please make sure to create the file does not exist!
///& lt;/summary>
///& lt; Typeparam name="T" & gt; Need the serial number of the target type & lt;/typeparam>
///& lt; Param name="filePath & gt;" Save the file path & lt;/param>
///& lt; Param name="target" & gt; Serial number of the target & lt;/param>
///& lt; Param name="fileMode & gt;" File operations mode & lt;/param>
Public static void Serializer (string filePath, T target, FileMode FileMode)
{
XmlSerializer XmlSerializer=new XmlSerializer (typeof (T)); Initial tools//
FileStream FileStream=new FileStream (filePath, fileMode);//use the document flow create file
XmlSerializer. Serialize (fileStream, target);//the serialization and save
FileStream. Close ();//close the file flow
FileStream. The Dispose ();//destruction of document flow
}

///& lt; Summary>
///will deserialized XML format file data for the target type
///& lt;/summary>
///& lt; Typeparam name="T" & gt; The target type & lt;/typeparam>
///& lt; Param name="filePath & gt;" The file path & lt;/param>
///& lt; Returns> Returns the target type data & lt;/returns>
Public static T Deserializer (string filePath)
{
XmlSerializer XmlSerializer=new XmlSerializer (typeof (T)); Initial tools//
FileStream FileStream=new FileStream (filePath, FileMode. Open);//using flow to open the file
T result=(T) xmlSerializer. Deserialize (fileStream);//deserialization and save
FileStream. Close ();//close the file flow
FileStream. The Dispose ();//destruction of document flow
return result;//return target
}
}


Has nothing to do with the serialization, seems and namespace oh

The following
 public class TestData 
{
Public int the age {get; set; }
Public string name {get; set; }
}

Private void button1_Click (object sender, EventArgs e)
{
List Datas=new List (a);
Datas. The Add (new TestData () {age=10, name="N1"});
Datas. The Add (new TestData () {age=12, name="N2"});
XmlTools. Serializer (" data. TXT ", datas, System. IO. FileMode. OpenOrCreate);
}
  •  Tags:  
  • C#
  • Related