net读取写入文件
写入分为续写和覆盖 只需改变第一个参数的值就可切换
代码如下:
/// <summary>
/// 内容写入到文本文件
/// </summary>
/// <param name="count">状态,判断是续写还是覆盖</param>
/// <param name="fileName">文件名称</param>
/// <param name="content">内容</param>
/// <returns>返回错误信息或时1代表写入成功</returns>
public static string writeFile(bool bl,string fileName, string content)
{
try
{
string pathName = System.Web.HttpContext.Current.Server.MapPath(fileName);
//这个不存在会自动创建
using (StreamWriter sw = new StreamWriter(pathName, bl, Encoding.Default))
{
sw.Write(content);
sw.Flush();
sw.Close();
}
}
catch (Exception ex)
{
return ex.Message;
}
return "1";
}
/// <summary>
/// 读取文本文件内容
/// </summary>
/// <param name="fileName">文件名称</param>
/// <returns>返回内容</returns>
public static string readFile(string fileName)
{
string result = "";
try
{
string pathName = System.Web.HttpContext.Current.Server.MapPath(fileName);
using (StreamReader sr = new StreamReader(pathName, Encoding.Default))
{
result = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
return "0";//ex.Message;
}
return result;
}