C# txt 文件数据写入与读取

写入

  1. 整体写入
 public static void  WriteFile(string path,string Mes)
        {
            FileStream fs = new FileStream(path, FileMode.Create);//创建文件流
            StreamWriter sw = new StreamWriter(fs);//创建写入器
            sw.Write(Mes);//已流的方式写入数据
            sw.Close();//关闭写入器
            fs.Close();//关闭文件流
        }
  1. 一行行写入数据
 public static void WriteByLine(string path,string DataLine)
        {
            FileStream fs = new FileStream(path, FileMode.Append);//创建文件流
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(DataLine);
            sw.Close();//关闭写入器
            fs.Close();//关闭文件流
        }

读取

  1. 整体读取
 public static string ReadFile(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open);   //创建文件流
            StreamReader sr = new StreamReader(fs, Encoding.Default);//创建读取器
            string Mes = sr.ReadToEnd();  //以流的方式读取文件
            sr.Close(); //关闭读取器
            fs.Close(); //关闭文件流
            return Mes;
        }
  1. 一行行读取
public static List<string> ReadByLine(string path)
    {
         FileStream fs = new FileStream(path, FileMode.Open);   //创建文件流
         StreamReader sr = new StreamReader(fs, Encoding.Default);//创建读取器
         List<string> Mes = new List<string>();
         string line;
         while ((line = sr.ReadLine()) != null)
         {
             Mes.Add(line);
         }
         sr.Close();
         fs.Close();
         return Mes;
     }
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值