读写文本文件之StreamReader和StreamWriter

时间:2022-11-29 21:37:27

private string _filePath = @"1.txt";

//查询文件是否存在,如果不存在,则创建

if (!File.Exists(_filePath))

{
using (File.Create(_filePath))
{

}
}

using (StreamReader sr = new StreamReader(_filePath))
{
//string str = sr.ReadLine();//读一行
string str = sr.ReadToEnd();//读到底
if (!string.IsNullOrWhiteSpace(str))
{
txtRtsp.Text = str;
}
}

//保存地址:
using (StreamWriter sw = new StreamWriter(_filePath)) //将覆盖原有内容
//using (StreamWriter sw = new StreamWriter(_filePath,true))//在原有内容上追加 
{
sw.Write(rtsp);
}

//循环读多行

String line;
                           while ((line = sr.ReadLine()) != null) 
                {
                    this.ListBox1.Items.Add("line ");   //增加读出的内容到listbox            
                    i++;
                }