//读取文件
public string Read(string path)
{
StreamReader sr=null ;
StringBuilder sb = new StringBuilder();
try
{
sr =new StreamReader(path, Encoding.UTF8);
String line;
while ((line = sr.ReadLine()) != null)
{
sb.Append(line + "\r\n");
}
}
catch (Exception ex)
{
}
finally
{
//清空缓冲区、关闭流
if (null != sr)
{
sr.Close();
}
}
return sb.ToString();
}
//读取文件
public void Write(string path, string fileName, string content)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
FileStream fs=null ;
try
{
fs = new FileStream(path + fileName, FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
//开始写入
fs.Write(data, 0, data.Length);
}
catch(Exception ex) {
}
finally {
//清空缓冲区、关闭流
if (null != fs)
{
fs.Flush();
fs.Close();
}
}
}
C# 读写文本文件
最新推荐文章于 2024-10-12 19:08:41 发布