由于用到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 ( ) ;
}
{
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 ( ) ;
}