C#中ListBox组件读写txt文件
2014-01-03 11:40
323 查看
C# 操作txt,使用的是流操作。主要用到的两个对象是StreamReader和StreamWriter。使用的对象方法是:ReadLine()一行一行读取和WriteLine()一行一行写入。
由于用到Stream对象,所以首先要引用System.IO命名空间:using System.IO;
引用后,定义StreamReader和StreamWriter对象:
private StreamReader _rstream = null;
private StreamWriter _wstream = null;
定义完成后,只需在使用的时候进行初始化如:
_rstream = new StreamReader(spath, System.Text.Encoding.Default); //读取 spath参数为需要读取的txt文件路径
_wstream = new StreamWriter(spath); //保存 spath 为文件保存的路径,有多个构造函数,可以指定文件是覆写还是追加。
初始化完成后,就可以调用方法对txt文件进行操作了,如下:
读文件:
_rstream.ReadLine()
写文件:
_wstream.Write(data);
_wstream.WriteLine();
读写完毕后,关闭释放对象
_rstream.Close(); //读文件后关闭
_wstream.Flush(); //写入流,并清理缓冲区
_wstream.Close(); //写文件后关闭
完整代码
private void WriteLstToTxt(ListBox
lst,string spath) //listbox
写入txt文件
{
int count = lst.Items.Count;
_wstream = new StreamWriter(spath);
for (int i = 0; i<count;i++){
string data = lst.Items[i].ToString();
_wstream.Write(data);
_wstream.WriteLine();
}
_wstream.Flush();
_wstream.Close();
}
private void ReadTxtToLst(ListBox
lst,string spath) //listbox
读取txt文件
{
_rstream = new StreamReader(spath, System.Text.Encoding.Default);
string line;
while ((line = _rstream.ReadLine()) != null)
{
lst.Items.Add(line);
}
_rstream.Close();
}
相关文章推荐
- C# txt文件读写
- [C#]解决读写包含汉字的txt文件时乱码的问题
- C# txt文件读写
- [转载]C#读写txt文件的两种方法介绍
- C#读写txt文件
- C#与TXT文件的读写操作
- C#读写txt文件的两种方法介绍
- C#读写txt文件的两种方法介绍
- C# 读写Txt文件
- C#简单读写txt文件的方法
- C#读写txt文件的方法
- [转载]C#读写txt文件的两种方法介绍
- C#读写记事本(txt)文件
- C# 1读写Excel 2创建文件读写入txt
- [C#]解决读写包含汉字的txt文件时乱码的问题
- C#读写txt文件的两种方法介绍
- [C#]解决读写包含汉字的txt文件时乱码的问题
- [C#]解决读写包含汉字的txt文件时乱码的问题
- C# 如何创建与读写txt文件
- C#读写txt文件多种方法实例代码