/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Name">文件名(包括后缀名)</param>
/// <param name="content">内容</param>
/// <returns></returns>
public static bool WriteFile(string Path, string Name, string content)
{
try
{
string path = HttpContext.Current.Server.MapPath(Path);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fname = HttpContext.Current.Server.MapPath(Path + "/" + Name);
if (!File.Exists(fname))
{
FileStream fs = File.Create(fname);
fs.Close();
}
StreamWriter sw = new StreamWriter(fname, false, System.Text.Encoding.GetEncoding("utf-8"));
sw.WriteLine(content);
sw.Close();
sw.Dispose();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 读文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static string ReadFile(string Path)
{
try
{
StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(Path), System.Text.Encoding.GetEncoding("utf-8"));
string content = sr.ReadToEnd().ToString();
sr.Close();
return content;
}
catch
{
return "<span style='color:red; font-size:x-large;'>Sorry,The Ariticle wasn't found!! It may have been deleted accidentally from Server.</span>";
}
}C#写入文件,与读取文件内容
最新推荐文章于 2026-05-14 06:25:10 发布
本文介绍了一个简单的文件读写方法实现,包括如何写入文件及从文件中读取内容。通过使用C#语言,实现了文件路径的映射、目录创建、文件创建及内容写入,并考虑了异常处理。

267

被折叠的 条评论
为什么被折叠?



