asp.net创建的子线程写文件引发拒绝访问错误

作者:Dreamer
出处:http://www.dreamerlzy.com/blog/article/detail/thread-writefile-accessdenied
说明:本文版权归作者所有,欢迎转载,但未经作者同意时,请在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
参考: 无

asp.net中创建的子线程有可能在写文件时抛出“拒绝访问错误”的异常,无法正确写入文件内容。
通过调试会发现asp.net子线程的用户权限和页面执行主线程的不同,造成拒绝访问错误。
目前我找到的解决方法是通过System.Security.Principal.WindowsIdentity.Impersonate方法,
在子线程里模拟主线程的“windows账户标记”从而获得和主线程相同权限。

protected void Page_Load(object sender, EventArgs e)
{   
 //先获得页面执行的主线程用户信息    
 System.Security.Principal.WindowsIdentity obj = System.Security.Principal.WindowsIdentity.GetCurrent();
 thread = new Thread(new ParameterizedThreadStart(proc));
 thread.Start(obj);
}
 
void proc(object obj)
{
 System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)obj;
    
 try
 {
  log.Write("test 0 start" + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
 }
 catch(Exception ex)
 {
  System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt", 
      "这里可能无法写入日志,会访问错误异常的,只是表示一下此处没有权限写入,后面模拟账号之后才能获得权限");
 }
 System.Security.Principal.WindowsIdentity.Impersonate(wi.Token); //模拟一下
 System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt", 
      "ok, 这里可以写入日志文件");
}
这只是手写的测试代码,可能有出入手误的地方,具体自己根据代码自己修改吧。某些情况下可能还需要web.config里进行一些修改,当然,如果可以配置iis的话,这些问题都不用考虑了,完全可以通过iis配置给更高的权限解决读写文件问题。