c#序列化与反序列化(文本)

时间:2022-02-24 07:35:21

using System.IO; using System.Runtime.Serialization.Formatters.Binary; public class Serialize { static public void DoSerialize<T>(T obj, string path) { using (FileStream fs = new FileStream(path, FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, obj); } } static public T DoDeSerialize<T>(string path) { FileInfo fi = new FileInfo(path); T t; try { using (FileStream fs = new FileStream(path, FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); t = (T)formatter.Deserialize(fs); } return t; } catch { return default(T); } } static public void SaveFile(string[] _content, string _path) { using (FileStream fs = new FileStream(_path, FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { for (int i = 0; i < _content.Length; i++) { sw.WriteLine(_content[i]); } } } } }