public static void WriteErrorLog(Exception ex)
{
string LOG_FOLDER = AppDomain.CurrentDomain.BaseDirectory + "Log";
try
{
//日志文件路径
filePath = LOG_FOLDER + "\\" + "ErrorLog" + ".txt";
if (!System.IO.Directory.Exists(LOG_FOLDER))
{
Directory.CreateDirectory(LOG_FOLDER);
}
if (!File.Exists(filePath))//如果文件不存在
{
File.Create(filePath);
}
StreamWriter sw = File.AppendText(filePath);
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine("Date:" + DateTime.Now.ToShortDateString() + " Time:" + DateTime.Now.ToShortTimeString());
sw.WriteLine(ex.Message);
sw.WriteLine(ex.StackTrace);
sw.WriteLine();
sw.Close();
}
catch (Exception)
{
//throw;
}
}
上面的,经常出现"**文件正由另一进程使用,因此该进程无法访问该文件"!!!!!!!!!!!!!!!
下面:
publicstaticvoid WriteLog(string _msg)
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/log");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
string filename = folder +"/"+ DateTime.Now.ToShortDateString() +".txt";
if (File.Exists(filename))
{
FileStream fs =new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sr =new StreamWriter(fs);
sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") +"\t"+ _msg);
sr.Close();
fs.Close();
}
else
{
FileStream fs =new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sr =new StreamWriter(fs);
sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") +"\t"+ _msg);
sr.Close();
fs.Close();
}
}