![](/img/trans.png)
[英]System.UnauthorizedAccessException: Access to the path:PATH is denied
[英]Exception: System.UnauthorizedAccessException, Message: Access to the path “” is denied
我有以下功能可以进行文本记录,但是我一直都在错误下方。 它不是每次都出现,而是在IIS级别上出现。 此错误后,IIS Apppool被停止。
发生未处理的异常,该过程已终止。
应用程序ID:/ LM / W3SVC / 2 / ROOT / OrderHelpDesk
流程编号:81044
异常:System.UnauthorizedAccessException
消息:拒绝访问路径'\\ Ser-file \\ ErrorLog \\ 2018-09 \\ 09_27_2018.txt'。
StackTrace:位于OrderHelpDesk.DAL.LogMessage(字符串消息),位于OrderHelpDesk.ViewPendingOrderDetails.AutoGenMailToCSRProcessed(实体objEntity),位于System.Threading.ExecutionContext.RunInternal(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值saveSyncCtx),位于System.Threading.Context。在System.Threading.ExecutionContext.Run(System.Threading.ThreadHelper.ThreadStart()处运行(ExecutionContextexecutionContext,ContextCallback回调,对象状态,布尔值saveSyncCtx)
public void LogMessage(string Message)
{
Entity objEntity = new Entity();
StreamWriter sw = null;
try
{
objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;
if (!Directory.Exists(objEntity.LogFilePath))
{
Directory.CreateDirectory(objEntity.LogFilePath);
}
sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt");
sw.WriteLine(objEntity.LogMessage);
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
sw.Close();
}
}
使用已经实现的日志库,例如NLog 。
如果你不能
发生这种情况是因为LogMessage可以被多个线程同时调用。 在这种情况下,一个线程将获取日志文件,而另一个线程将获取AccessDenied,并且由于sw为null,所以您的池将崩溃,但是您调用sw.Close()。 使用同步原语并使用构造(或检查sw是否为null sw?.Close()):
static object locker = new object();
public void LogMessage(string Message)
{
lock (locker)
{
Entity objEntity = new Entity();
objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;
if (!Directory.Exists(objEntity.LogFilePath))
{
Directory.CreateDirectory(objEntity.LogFilePath);
}
using (StreamWriter sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt"))
{
sw.WriteLine(objEntity.LogMessage);
}
}
}
这可能是文件/文件夹权限的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.