Add class and copy this code into it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
namespace WindowsFormsApplication6
{
enum
SerialiaztionMethod
{
Soap ,
Binary
}
class SaveGameState
{
public SaveGameState(SerialiaztionMethod method ,
Object obj , string
path)
{
this.SerialiaztionType = method;
this.Obj = obj;
this.MyPath = path;
}
public
SerialiaztionMethod SerialiaztionType
{
get;
set;
}
public string
MyPath
{
get;
set;
}
public Object
Obj
{
get;
set;
}
public void
Serialization()
{
if (SerialiaztionType ==
SerialiaztionMethod.Binary)
{
using (FileStream
fstream =new
FileStream(MyPath, FileMode.OpenOrCreate))
{
BinaryFormatter bf =
new BinaryFormatter();
bf.Serialize(fstream ,Obj);
}
}
else if
(SerialiaztionType == SerialiaztionMethod.Soap)
{
using (FileStream
fstream = new
FileStream(MyPath, FileMode.OpenOrCreate))
{
SoapFormatter bf =
new SoapFormatter();
bf.Serialize(fstream, Obj);
}
}
}
public object
DeSerialization()
{
if (SerialiaztionType ==
SerialiaztionMethod.Binary)
{
using (FileStream
fstream = new
FileStream(MyPath, FileMode.OpenOrCreate))
{
BinaryFormatter bf =
new BinaryFormatter();
return bf.Deserialize(fstream);
}
}
else if
(SerialiaztionType == SerialiaztionMethod.Soap)
{
using (FileStream
fstream = new
FileStream(MyPath, FileMode.OpenOrCreate))
{
SoapFormatter bf =
new SoapFormatter();
return bf.Deserialize(fstream);
}
}
else
{
return null;
}
}
}
}
in Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
public partial
class Form1 :
Form
{
SaveGameState saveGame =
null;
public Form1()
{
InitializeComponent();
}
PersonalDetails p =
new PersonalDetails();
// Serialization.
private void
btnSet_Click(object sender,
EventArgs e)
{
p.ID = int.Parse(textBox1.Text);
p.Name = textBox2.Text;
p.Age = textBox3.Text;
saveGame = new
SaveGameState(SerialiaztionMethod.Soap,
p, "c:\\SaveObjetFile.xml");
saveGame.Serialization();
}
// DeSerialization.
private void
btnGet_Click(object sender,
EventArgs e)
{
p = saveGame.DeSerialization() as
PersonalDetails;
textBox4.Text = p.ID.ToString();
textBox5.Text = p.Name;
textBox6.Text = p.Age;
}
private void
btnRest_Click(object sender,
EventArgs e)
{
EmptyTextBox();
}
private void
EmptyTextBox()
{
foreach (Control
cntrl in Controls)
{
if (cntrl is
TextBox)
{
cntrl.Text = "";
}
}
}
}
[Serializable]
// Attribute.
// Attribute.
class
PersonalDetails
{
public int
ID { get; set; }
public string
Name { get; set;
}
public string
Age { get; set;
}
}
}
0 التعليقات:
إرسال تعليق