AceInfinity
Emeritus, Contributor
Here's an example of serialization I've put together. What this allows you to do is to retrieve data from a file and save class object data to that file for later use. You'll notice the serializable object we have, is our TLFUser class marked with the Serializable attribute, so that we can serialize this object using the SOAP format.
Before you begin, you'll need to add these to the top of your code for references:
And you'll also need to manually add the reference for System.Runtime.Serialization.Formatters.Soap.
Here's the data we want to serialize:
And here's our method:
You should be able to see how this can come in useful, otherwise ask your questions :)
:beerchug2:
Before you begin, you'll need to add these to the top of your code for references:
C#:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Soap;
And you'll also need to manually add the reference for System.Runtime.Serialization.Formatters.Soap.
Here's the data we want to serialize:
C#:
[Serializable]
public class TLFUser
{
public string Username;
public int UID;
public string GroupName;
public int GID;
public TLFUser(string name, int uid, string groupname, int gid)
{
this.Username = name;
this.UID = uid;
this.GroupName = groupname;
this.GID = gid;
}
public string DisplayData()
{
return string.Format("{0}\r\n{1}\r\n{2}\r\n{3}", this.Username, this.UID, this.GroupName, this.GID);
}
}
And here's our method:
C#:
private void MainMethod()
{
SerializeData(SerializeOptions.Deserialize);
}
private enum SerializeOptions
{
Serialize,
Deserialize
}
private void SerializeData(SerializeOptions Opt)
{
string filePath = string.Format(@"{0}\test.xml", Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
TLFUser TLFuser;
switch (Opt)
{
case SerializeOptions.Serialize:
TLFuser = new TLFUser("AceInfinity", 1, "Administrators", 4);
if (SOAPSerialize<TLFUser>(filePath, TLFuser))
{
MessageBox.Show("Successful serialization!");
}
break;
case SerializeOptions.Deserialize:
if (SOAPDeserialize<TLFUser>(filePath, out TLFuser))
{
MessageBox.Show("Successful deserialization!");
textBox1.Text = TLFuser.DisplayData();
}
break;
}
}
private bool SOAPSerialize<T>(string filePath, T ClassData)
{
FileStream fs = new FileStream(filePath, System.IO.FileMode.CreateNew);
try
{
SoapFormatter soap = new SoapFormatter();
soap.Serialize(fs, ClassData);
}
catch (SerializationException)
{
return false;
}
finally
{
fs.Close();
}
return true;
}
private bool SOAPDeserialize<T>(string filePath, out T ClassObj)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
try
{
SoapFormatter soap = new SoapFormatter();
ClassObj = (T)soap.Deserialize(fs);
}
catch (SerializationException)
{
ClassObj = default(T);
return false;
}
finally
{
fs.Close();
}
return true;
}
You should be able to see how this can come in useful, otherwise ask your questions :)
:beerchug2: