C# 读写TXT文件操作

Love朴啾啾 2024-06-15 08:35:03 阅读 52

一 、读取文本文件有多种方法

1 使用 StreamReader 类打开、读取和关闭文本文件。使用 ReadLine 方法逐行读取文本文件,ReadToEnd方法将文本文件读取到末尾。

/// <summary> /// 逐行将文本文件读取到末尾 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_StreamReader(string pathAName) { StreamReader ObjectName = new StreamReader(pathAName); return ObjectName.ReadToEnd(); }

2、StreamReader继承TextReader,操作和StreamReader一致,使用 ReadLine 方法逐行读取文本文件,ReadToEnd方法将文本文件读取到末尾。

/// <summary> /// 逐行读取文件,返回列表 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static List<string> ReadTXT_TextReader(string pathAName) { List<string> txtContent = new List<string>(); if (!File.Exists(pathAName)) { using (TextReader reader = new StreamReader(pathAName)) { string line; while ((line = reader.ReadLine()) != null) // 逐行读取文件内容 { txtContent.Add(line); // 输出每行内容到控制台 } } } return txtContent; }

3、使用 File 类打开、读取和关闭文本文件。

File.ReadAllLines(string path, Encoding encoding) 方法:打开一个文件,使用指定的编码读取文件的所有行,然后关闭该文件。返回包含文件所有行的字符串数组。

/// <summary> /// 逐行读取文件,返回数组 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string[] ReadTXT_ReadAllLines(string pathAName) { string[] txtContent = null; txtContent = System.IO.File.ReadAllLines(pathAName, Encoding.UTF8); return txtContent; }

File.ReadAllText(string path, Encoding encoding)方法:打开一个文件,使用指定的编码读取文件的所有行,然后关闭该文件。逐行读取文本文件。返回包含文件所有行的字符串。

/// <summary> /// 读取,返回字符串 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_ReadAllText(string pathAName) { string txtContent = null; txtContent = System.IO.File.ReadAllText(pathAName, Encoding.UTF8); return txtContent; }

ReadLines(string path, Encoding encoding)方法:读取具有指定编码的文件的文本行。返回该文件的所有行或查询所示的行。

/// <summary> /// 读取,返回枚举类型 /// 高效地逐行读取大型文本文件的最佳方法 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_ReadLines(string pathAName) { IEnumerable<string> line = System.IO.File.ReadLines(pathAName, Encoding.UTF8); return String.Join(Environment.NewLine, line); }

二、创建、写入文本文件

1、FileStream 创建文件,可设置文件属性,StreamWriter 打开、写入、关闭文件。

a)方式1:

/// <summary> /// 数据流形式写入文件 /// </summary> /// <param name="path"></param> /// <param name="txtContent"></param> /// <returns></returns> public static void WriteTXT_StreamWriter(string pathAName, string txtContent) { FileStream fs; //判断是否已经有了这个文件 if (!System.IO.File.Exists(pathAName)) { //没有则创建这个文件,创建写入文件,设置文件属性为隐藏 fs = new FileStream(pathAName, FileMode.Create, FileAccess.Write); } else { fs = new FileStream(pathAName, FileMode.Open, FileAccess.Write); } File.SetAttributes(@pathAName, FileAttributes.Hidden); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(txtContent.Trim());//写入值 sw.Flush(); sw.Dispose(); sw.Close(); fs.Close(); }

b)方式2

/// <summary> /// 数据流形式写入文件 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void Write(string pathAName, string Logstring) { if (!File.Exists(pathAName)) { //创建.txt文件 FileStream stream = File.Create(pathAName); stream.Close(); stream.Dispose(); } // true:若文件存在,则将数据追加到该文件中若要覆盖该文件 using (StreamWriter writer = new StreamWriter(pathAName, true)) { //写入文件 writer.WriteLine(Logstring); writer.Close(); } }

2、StreamWriter 继承 TextWriter ,StreamWriter 创建、打开、WriteLine 写入文件

/// <summary> /// 创建、写入文本文档 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void WriteTXT_TextWriter(string pathAName, string Logstring) { if (!File.Exists(pathAName)) { using (TextWriter reader = new StreamWriter(pathAName)) { reader.WriteLine(Logstring.Trim()); } } }

3、使用 File 类创建、写入和关闭文本文件

WriteAllText(string path, string contents) 方法:创建一个新文件,在其中写入指定的字符串,然后关闭文件。如果目标文件已存在,则覆盖该文件。

/// <summary> /// 在最开始位置追加,追加到开头 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void AddTextFirst(string pathAName, string Logstring) { string s = File.ReadAllText(pathAName); s = s.Insert(0, Logstring.Trim() + "\r\n"); File.WriteAllText(pathAName, s); }

WriteAllLines(string path, string[] contents) :创建一个新文件,在其中写入指定的字符串数组,然后关闭该文件。

/// <summary> /// File.WriteAllLines 方法用于将字符串数组的内容按行写入文本文件。 /// 每个数组元素都被写入文件的一行,且方法会自动在每行的末尾添加换行符。 /// </summary> /// <param name="Logstring"></param> /// <param name="pathAName"></param> public static void WriteTXT(string pathAName,string []Logstring) { File.WriteAllLines(pathAName, Logstring);//写入文件 }

4、在最开始位置追加,追加到开头

/// <summary> /// 在最开始位置追加,追加到开头 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void AddTextFirst(string pathAName, string Logstring) { string s = File.ReadAllText(pathAName); s = s.Insert(0, Logstring.Trim() + "\r\n"); File.WriteAllText(pathAName, s); }

5、在最后位置追加

/// <summary> /// 在最后位置追加 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void AddTextEnd(string pathAName, string Logstring) { StreamWriter sw = File.AppendText(pathAName); sw.WriteLine(Logstring.Trim()); sw.Close(); }

三、使用实例

OpenFileDialog openFileDialog1; SaveFileDialog saveFileOpen; string dir = null; public Form1() { InitializeComponent(); dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); openFileDialog1 = new OpenFileDialog(); openFileDialog1.Title = "导入"; openFileDialog1.Filter = "TXT文件|*.txt"; openFileDialog1.Multiselect = false; openFileDialog1.RestoreDirectory = true; openFileDialog1.InitialDirectory = dir; saveFileOpen = new SaveFileDialog(); saveFileOpen.Title = "保存文件"; saveFileOpen.Filter = "TXT文件(*.txt)|*.txt"; saveFileOpen.RestoreDirectory = true; saveFileOpen.InitialDirectory = dir; } private void richTextBox1_TextChanged(object sender, EventArgs e) { richTextBox1.ScrollToCaret(); } /// <summary> /// 读入txt文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { string info = null; string txtContent = null; if (openFileDialog1.ShowDialog() == DialogResult.OK) { info = openFileDialog1.FileName; } if (!string.IsNullOrEmpty(info)) { txtContent = OperateTXT.ReadTXT_StreamReader(info); richTextBox1.AppendText(txtContent); } } /// <summary> /// 写入txt文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string now_date = DateTime.Now.ToString("MMddHHmmss") + ".txt"; string newPath = System.IO.Path.Combine(dir, now_date); saveFileOpen.FileName = newPath; //设置默认另存为的名字 if (saveFileOpen.ShowDialog() == DialogResult.OK) { newPath = saveFileOpen.FileName; } OperateTXT.WriteTxt(newPath, richTextBox1.Text); }

在这里插入图片描述

静态操作使用类

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;namespace FileOperationsDemo{ public static class OperateTXT { #region 写入文件 /// <summary> /// 数据流形式写入文件 /// </summary> /// <param name="path"></param> /// <param name="txtContent"></param> /// <returns></returns> public static void WriteTXT_StreamWriter(string pathAName, string txtContent) { FileStream fs; //判断是否已经有了这个文件 if (!System.IO.File.Exists(pathAName)) { //没有则创建这个文件,创建写入文件,设置文件属性为隐藏 fs = new FileStream(pathAName, FileMode.Create, FileAccess.Write); } else { fs = new FileStream(pathAName, FileMode.Open, FileAccess.Write); } File.SetAttributes(@pathAName, FileAttributes.Hidden); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(txtContent.Trim());//写入值 sw.Flush(); sw.Dispose(); sw.Close(); fs.Close(); } /// <summary> /// 数据流形式写入文件 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void Write(string pathAName, string Logstring) { if (!File.Exists(pathAName)) { //创建.txt文件 FileStream stream = File.Create(pathAName); stream.Close(); stream.Dispose(); } // true:若文件存在,则将数据追加到该文件中若要覆盖该文件 using (StreamWriter writer = new StreamWriter(pathAName, true)) { //写入文件 writer.WriteLine(Logstring); writer.Close(); } } /// <summary> /// 创建、写入文本文档 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void WriteTXT_TextWriter(string pathAName, string Logstring) { if (!File.Exists(pathAName)) { using (TextWriter reader = new StreamWriter(pathAName)) { reader.WriteLine(Logstring.Trim()); } } } /// <summary> /// File.WriteAllText 方法用于将单个字符串写入文本文件。 /// 整个字符串将写入文件,不会自动添加换行符。 /// 如果需要在字符串中包含换行,需要手动添加换行符。 /// </summary> /// <param name="Logstring"></param> /// <param name="pathAName"></param> public static void WriteTxt(string pathAName, string Logstring) { File.WriteAllText(pathAName, Logstring);//写入文件 } /// <summary> /// File.WriteAllLines 方法用于将字符串数组的内容按行写入文本文件。 /// 每个数组元素都被写入文件的一行,且方法会自动在每行的末尾添加换行符。 /// </summary> /// <param name="Logstring"></param> /// <param name="pathAName"></param> public static void WriteTXT(string pathAName,string []Logstring) { File.WriteAllLines(pathAName, Logstring);//写入文件 } /// <summary> /// 在最开始位置追加,追加到开头 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void AddTextFirst(string pathAName, string Logstring) { string s = File.ReadAllText(pathAName); s = s.Insert(0, Logstring.Trim() + "\r\n"); File.WriteAllText(pathAName, s); } /// <summary> /// 在最后位置追加 /// </summary> /// <param name="pathAName"></param> /// <param name="Logstring"></param> public static void AddTextEnd(string pathAName, string Logstring) { StreamWriter sw = File.AppendText(pathAName); sw.WriteLine(Logstring.Trim()); sw.Close(); } #endregion #region 读取文件 /// <summary> /// 将文本文件读取到末尾 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_StreamReader(string pathAName) { StreamReader ObjectName = new StreamReader(pathAName); return ObjectName.ReadToEnd(); } /// <summary> /// 逐行读取文件,返回列表 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static List<string> ReadTXT_TextReader(string pathAName) { List<string> txtContent = new List<string>(); if (!File.Exists(pathAName)) { using (TextReader reader = new StreamReader(pathAName)) { string line; while ((line = reader.ReadLine()) != null) // 逐行读取文件内容 { txtContent.Add(line); // 输出每行内容到控制台 } } } return txtContent; } /// <summary> /// 逐行读取文件,返回数组 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string[] ReadTXT_ReadAllLines(string pathAName) { string[] txtContent = null; txtContent = System.IO.File.ReadAllLines(pathAName, Encoding.UTF8); return txtContent; } /// <summary> /// 读取,返回字符串 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_ReadAllText(string pathAName) { string txtContent = null; txtContent = System.IO.File.ReadAllText(pathAName, Encoding.UTF8); return txtContent; } /// <summary> /// 读取,返回枚举类型 /// 高效地逐行读取大型文本文件的最佳方法 /// </summary> /// <param name="pathAName"></param> /// <returns></returns> public static string ReadTXT_ReadLines(string pathAName) { IEnumerable<string> line = System.IO.File.ReadLines(pathAName, Encoding.UTF8); return String.Join(Environment.NewLine, line); } #endregion }}



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。