随便写的,主代码:
[C#] 纯文本查看 复制代码
public class SerializeHelper<T>
{
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj">要进行序列化的对象</param>
/// <param name="fileName">保存路径</param>
public void SerializeNow(T obj, string fileName)
{
var fileStream = new FileStream(fileName, FileMode.Create);
var b = new BinaryFormatter();
b.Serialize(fileStream, obj);
fileStream.Close();
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="fileName">要进行反序列化的文件</param>
/// <returns>结果</returns>
public T DeSerializeNow(string fileName)
{
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter b = new BinaryFormatter();
var obj = b.Deserialize(fileStream);
fileStream.Close();
T result = default(T);
if (obj is T)
{
result = (T)obj;
}
return result;
}
}
使用方法:
[C#] 纯文本查看 复制代码 //序列化
var serialize = new SerializeHelper<SettingModel>();
var setting = new SettingModel();
setting.SqlString = txtSqlIP.Text;
setting.SqlUser = txtSqlUser.Text;
setting.SqlPassword = txtSqlPassword.Text;
setting.SqlDbName = txtSqlDbName.Text;
setting.SqlPort = txtSqlPort.Text;
setting.VersionStopMsg = txtVersionStopMsg.Text;
serialize.SerializeNow(setting, "Setting.dat");
//反序列化
var SettingModel = new Setting.SettingModel();
SettingModel = serialize.DeSerializeNow("Setting.dat");
|