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 = 0;
while (sr.Peek() > 0)
{
lineCount++;
string temp = sr.ReadLine();
txt.Add(temp);
}
}
}
return txt;
}
其中
1 using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default))
2 {
3 int lineCount = 0;
4 while (sr.Peek() > 0)
5 {
6 lineCount++;
7 string temp = sr.ReadLine();
8 txt.Add(temp);
9 }
10 }
StreamReader 是以流的方式逐行将TxT内容保存到List<string> txt中。
其次,对TxT文件的写入操作,也是将数组List<string> 中的每个元素逐行写入到TxT中,并保存为.txt文件。且看代码:
1 SaveFileDialog sf = new SaveFileDialog();
2 sf.Title = "Save text Files";
3 sf.DefaultExt = "txt";
4 sf.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
5 sf.FilterIndex = 1;
6 sf.RestoreDirectory = true;
7 if ((bool)sf.ShowDialog())
8 {
9 using (FileStream fs = new FileStream(sf.FileName, FileMode.Create))
10 {
11 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
12 {
13 for (int i = 0; i < txt.Count; i++)
14 {
15 sw.WriteLine(txt[i]);
16 }
17 }
18 }
19
20 }
而在这之中,相对于读入TxT文件相比,在写的时候,多用到了 FileStream类。
