最近对文件的操作比较频繁。这里记录一下常用的几种文件读写的方式。
我这里使用窗体来做测试,例子在文末,可下载。
1:二进制读写
BinaryReader 类
BinaryReader 类用于从文件读取二进制数据。一个 BinaryReader 对象通过向它的构造函数传递 FileStream 对象而被创建。
BinaryWriter 类
BinaryWriter 类用于向文件写入二进制数据。一个 BinaryWriter 对象通过向它的构造函数传递 FileStream 对象而被创建。
实例如下:
ini
复制代码
/// <summary> /// 二进制写入文件 /// </summary> private void button1_Click(object sender, EventArgs e) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.FileName = "File"; saveDlg.Title = "保存数据"; saveDlg.Filter = "File(*.txt)|*.txt"; saveDlg.DefaultExt = "txt"; saveDlg.AddExtension = true; //saveDlg.InitialDirectory = "D:AMC Results"; if (saveDlg.ShowDialog() == DialogResult.OK) { Cursor = Cursors.WaitCursor; SaveDatafileWithNewVersion(saveDlg.FileName); Cursor = Cursors.Default; } } /// <summary> /// 二进制保存文件 /// </summary> public static void SaveDatafileWithNewVersion(String sFile) { //文件格式依次为:内部版本号,... Stream stream = File.Open(sFile, FileMode.Create); BinaryWriter bw = new BinaryWriter(stream); bw.Write((Int16)1);//内部版本号,暂时用1,表示版本1,整型 ///写入Config对象 bw.Write("泽国江山入战图 "); bw.Write("生民何计乐樵苏 "); bw.Write("凭君莫话封侯事 "); bw.Write("一将功成万骨枯 "); bw.Close(); stream.Close(); } /// <summary> /// 打开文件 /// </summary> private void button2_Click(object sender, EventArgs e) { OpenFileDialog openDlg = new OpenFileDialog(); openDlg.Title = "File"; openDlg.Filter = "File (*.txt)|*.txt"; if (openDlg.ShowDialog() == DialogResult.OK) { BinaryReader br = new BinaryReader(new FileStream(openDlg.FileName, FileMode.Open)); string str = ""; int number = br.ReadInt16(); str += br.ReadString(); str += br.ReadString(); str += br.ReadString(); str += br.ReadString(); richTextBox1.Text = str; br.Close(); } }
2:泛型读写:
ini
复制代码
/// <summary> /// 泛型写入 /// </summary> private void button3_Click(object sender, EventArgs e) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.FileName = "File"; saveDlg.Title = "保存数据"; saveDlg.Filter = "File(*.txt)|*.txt"; saveDlg.DefaultExt = "txt"; saveDlg.AddExtension = true; //saveDlg.InitialDirectory = "D:AMC Results"; if (saveDlg.ShowDialog() == DialogResult.OK) { string str = "泽国江山入战图 生民何计乐樵苏 凭君莫话封侯事 一将功成万骨枯 "; BinarySerialize<string>(str, saveDlg.FileName); } } /// <summary> /// 写入文件 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="obj">写入类型</param> /// <param name="path">路径</param> public static void BinarySerialize<T>(T obj, string path) { FileStream fileStream = new FileStream(path, FileMode.Create); BinaryFormatter b = new BinaryFormatter(); try { b.Serialize(fileStream, obj); fileStream.Close(); } catch (System.Exception ex) { Console.WriteLine(ex.Message); } finally { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } } /// <summary> /// 泛型读取 /// </summary> private void button4_Click(object sender, EventArgs e) { OpenFileDialog openDlg = new OpenFileDialog(); openDlg.Title = "File"; openDlg.Filter = "File (*.txt)|*.txt"; if (openDlg.ShowDialog() == DialogResult.OK) { string str = BinaryDeserialize<string>(openDlg.FileName); richTextBox2.Text = str; } } /// <summary> /// 读取文件 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="path">路径</param> /// <returns></returns> public static T BinaryDeserialize<T>(string path) { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFormatter b = new BinaryFormatter(); //SoapFormatter T rs; try { rs = (T)b.Deserialize(fileStream); return rs; } catch (System.Exception ex) { Console.WriteLine(ex.Message); } finally { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } return default(T); }
3:XML读写:不是很稳定
什么是XML呢?
- XML 指可扩展标记语言(EXtensible Markup Language)
- XML 是一种标记语言,很类似HTML
- XML 的设计宗旨是传输数据,而非显示数据
- XML 标签没有被预定义,您需要自行定义标签
- XML 被设计为具有自我描述性
- XML 是W3C 的推荐标准
实例如下:
csharp
复制代码
/// <summary> /// XML写入 /// </summary> private void button5_Click(object sender, EventArgs e) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.FileName = "File"; saveDlg.Title = "保存数据"; saveDlg.Filter = "File(*.txt)|*.txt"; saveDlg.DefaultExt = "txt"; saveDlg.AddExtension = true; //saveDlg.InitialDirectory = "D:AMC Results"; if (saveDlg.ShowDialog() == DialogResult.OK) { string str = "泽国江山入战图 生民何计乐樵苏 凭君莫话封侯事 一将功成万骨枯 "; SerializeToXml<string>(saveDlg.FileName, str); } } /// <summary> /// XML序列化某一类型到指定的文件 /// /// </summary> /// /// <param name="filePath">文件路径</param> /// /// <param name="obj">写入对象</param> /// /// <param name="type"></param> public static void SerializeToXml<T>(string filePath, T obj) { try { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath)) { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T)); xs.Serialize(writer, obj); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } /// <summary> /// XML读取 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button6_Click(object sender, EventArgs e) { OpenFileDialog openDlg = new OpenFileDialog(); openDlg.Title = "File"; openDlg.Filter = "File (*.txt)|*.txt"; if (openDlg.ShowDialog() == DialogResult.OK) { string str = DeserializeFromXml<string>(openDlg.FileName); richTextBox3.Text = str; } } /// <summary> /// 从某一XML文件反序列化到某一类型 /// </summary> /// <param name="filePath">待反序列化的XML文件名称</param> /// <param name="type">反序列化出的</param> /// <returns></returns> public static T DeserializeFromXml<T>(string filePath) { try { if (!System.IO.File.Exists(filePath)) throw new ArgumentNullException(filePath + " not Exists"); using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath)) { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T)); T ret = (T)xs.Deserialize(reader); return ret; } } catch (Exception ex) { Console.WriteLine(ex.Message); return default(T); } }
最终效果:
如果有更好的方法,欢迎在下边留言补充。
原文链接:点击这里,走你
欢迎访问个人博客guanchao.site