1、实现每日输出一个日志文件
2、解决c#读写LOG文件提示被其他进程占用问题
/// <summary>
/// 每日新建一个日志文件,解决c#读写LOG文件提示被其他进程占用问题
/// </summary>
public static bool showLogStr { get; set; }
private static object o = new object();
public static void writeLog(string logType, string msgStr)
{
//输出日志
bool showLog = false;
showLog = showLogStr;
//输出日志
if (showLog)
{
CreateDirectory(pathStr);
string logPath = pathStr + "\\log_" + logType + "_" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt";
ThreadPool.QueueUserWorkItem(new WaitCallback(obj =>//线程池,在线程池有线程变得可用时执行
{
lock (o)
{
using (var sw = new StreamWriter(logPath, true))
{
string dataStr = "【" + DateTime.Now.ToLongTimeString().ToString() + "】:";
dataStr += msgStr;
sw.WriteLine(dataStr);
sw.Flush();
sw.Close();
}
}
}));
}
}
private static void CreateDirectory(string path)
{
if (System.IO.Directory.Exists(path) == false)//如果不存在就创建file文件夹
{
System.IO.Directory.CreateDirectory(path);
}
}