mvc 读写txt文档

-----------------写入内容----------------

string userfile = "UserData.txt";
StreamWriter sw = null;

//判断是否存在
if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(@"../" + userfile)))
{

  //不存在,新建
  System.IO.File.Create(System.Web.HttpContext.Current.Server.MapPath(@"../" + userfile)).Close();
  sw = new StreamWriter(Server.MapPath(@"../" + userfile), true, System.Text.Encoding.Default);

  sw.Write("用户名");
  sw.Write("," + "手机号");
  sw.Write("," + "地址");
  sw.WriteLine();
}
else
{
  sw = new StreamWriter(Server.MapPath(@"../" + userfile), true, System.Text.Encoding.Default);
}

  sw.Write(“想要写入的内容”);
  sw.WriteLine();
  sw.Close(); //关闭流

-----------------读取内容----------------

string uListPath = @"../" + "UserData.txt";

string content = string.Empty;
if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(uListPath)))
{
  //文件不存在
}
else
{
  using (StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(uListPath),   System.Text.Encoding.Default))
  {
    content = sr.ReadToEnd(); // 读取txt文件内容
  }
}

原文地址:https://www.cnblogs.com/yao3364/p/8708550.html