如果文件不是多线程写入,用这个写入比较方便,不用引用第三方库,如果是高频写日志建议用Log4net,相关的log4net方法请访问C#, .Net添加log4net日志功能-罗分明网络博客 (luofenming.com)
/// <summary> /// 写日志方法 /// </summary> /// <param name="pathStr">日志存放位置</param> /// <param name="msg">日志内容</param> public void WriteLog(string pathStr, string msg) { string tempPath = Path.GetDirectoryName(pathStr);//获得文件的目录 if (!Directory.Exists(tempPath))//如果没有文件指定的目录就创建 { Directory.CreateDirectory(tempPath); } using (StreamWriter sw = new StreamWriter(pathStr, true)) { sw.Write(msg); } } /// <summary> /// 读取文件内容,注意要读取的文本不要太大 /// </summary> /// <param name="pathStr"></param> /// <returns></returns> public string ReadLog(string pathStr) { if (File.Exists(pathStr)) { using (StreamReader sr = new StreamReader(pathStr, true)) { return sr.ReadToEnd(); } } return string.Empty; }
方法调用
string path = AppDomain.CurrentDomain.BaseDirectory + "/temp/1.txt"; WriteLog(path, "测试写入文件"); string s = ReadLog(path);
本文来自www.luofenming.com