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 object 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(); return obj; } } 以上为主要代码,那么在程序中调用如下: //序列化 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") as Setting.SettingModel;
来源:https://www.cnblogs.com/liqie/p/5699074.html