C#中读取和写入文本内容
因为之前使用filestrean读取,取到的uf8的内容不如愿。遇到了一些困难所以改变读取策略。
所以改成了streamreader读取。
这是一个完整了类粘贴进去就可以使用了。
/// <summary>
/// 读写txt文件的类
/// </summary>
public class txtRW
{
/// <summary>
/// 传递路径,打开文本读取内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string ReadTxt(string path)
{
string text = "";
try
{
StreamReader sr = new StreamReader(path);
text =sr.ReadToEnd();
sr.Close();
sr.Dispose();
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return "";
}
return text;
}
/// <summary>
/// 将内容写入指定的路径
/// </summary>
public void WriteTxt(string path,string text)
{
FileStream fs = new FileStream(path, FileMode.Append);
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(text);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
}
posted on 2016-03-18 14:06 forgive-me 阅读(167) 评论(0) 编辑 收藏 举报