Windows service spontaneously losing access to temp folder

时间:2017-08-04 12:46:22

标签: c# windows-services temp unauthorizedaccessexcepti

I have a Windows service application that, as part of processing MSMQ messages, writes out to the TEMP directory of the account under which it is running. So, if the service were running under MYDOMAIN\foo, the TEMP directory would be C:\Users\foo\AppData\Local\Temp\. The relevant code is:

Guid key = Guid.NewGuid();
string tempPdf = Path.Combine(Path.GetTempPath(), string.Format("{0:D}.pdf", key));
byte[] output = GetSomeData();  // Gets in-memory PDF data, in this case the output from an SSRS report
File.WriteAllBytes(tempPdf, output);

This normally works without any problems. At seemingly random intervals (sometimes a couple of times in one day, sometimes a couple of days between) the process will start to fail on the File.WriteAllBytes call. The exception is:

System.UnauthorizedAccessException: Access to the path 'C:\Users\foo\AppData\Local\Temp\a2b5b6b0-7c25-42a4-a475-771b8f4c525e.pdf' is denied.

Restarting the service fixes everything, at least temporarily.

Disk space is fine. Permissions seem normal for a TEMP folder. There is nothing of interest in the Event Log other than the application error above. This is running on Windows Server 2012 R2.

Stack trace:

System.UnauthorizedAccessException: Access to the path 'C:\Users\foo\AppData\Local\Temp\eb29dd49-d3c5-486f-8a9b-fface4857448.pdf' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)

Any ideas what could be causing this, or tips to track down where the problem might be?

1 个答案:

答案 0 :(得分:1)

这最终成为冒充问题。有一个完全独立的进程,在同一个Windows服务下运行,在模拟调用中封装了一些代码。该代码没有干净地实现,因此未处理的异常将无法终止模拟,因此其他(不相关的)进程仍在模拟帐户下运行,这显然无法访问服务用户临时文件夹。

在运行Process Monitor并查看ACCESS DENIED事件的详细信息后,我能够看到这一点。

相关问题