C#中ListBox组件读写txt文件

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 ( ) ;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值