C#读写TxT文件

时间:2023-03-09 19:31:51
C#读写TxT文件

文/嶽永鹏

WPF 中读取和写入TxT 是经常性的操作,本篇将从详细演示WPF如何读取和写入TxT文件。

首先,TxT文件希望逐行读取,并将每行读取到的数据作为一个数组的一个元素,因此需要引入List<string> 数据类型。且看代码:

 public List<string> OpenTxt(TextBox tbx)
{
List<string> txt = new List<string>();
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "文本文件(*.txt)|*.txt|(*.rtf)|*.rtf";
if (openFile.ShowDialog() == true)
{
tbx.Text = "";
using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default))
{
int lineCount = ;
while (sr.Peek() > )
{
lineCount++;
string temp = sr.ReadLine();
txt.Add(temp);
}
} }
return txt;
}

其中

  using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default))
{
int lineCount = ;
while (sr.Peek() > )
{
lineCount++;
string temp = sr.ReadLine();
txt.Add(temp);
}
10 }

StreamReader 是以流的方式逐行将TxT内容保存到List<string> txt中。

其次,对TxT文件的写入操作,也是将数组List<string> 中的每个元素逐行写入到TxT中,并保存为.txt文件。且看代码:

 SaveFileDialog sf = new SaveFileDialog();
sf.Title = "Save text Files";
sf.DefaultExt = "txt";
sf.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
sf.FilterIndex = ;
sf.RestoreDirectory = true;
if ((bool)sf.ShowDialog())
{
using (FileStream fs = new FileStream(sf.FileName, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
for (int i = ; i < txt.Count; i++)
{
sw.WriteLine(txt[i]);
}
}
} }

而在这之中,相对于读入TxT文件相比,在写的时候,多用到了 FileStream类。