Search code examples
c#windows-servicestempunauthorizedaccessexcepti

Windows service spontaneously losing access to temp folder


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?


Solution

  • This ended up being an impersonation problem. There was a completely separate process, running under the same Windows service, that encapsulated some code in an impersonation call. That code was not implemented cleanly, such that an unhandled exception would fail to terminate the impersonation, so that other (unrelated) processes were still running under the impersonated account which obviously didn't have access to the service user's temp folder.

    I was able to see this after running Process Monitor and viewing the details for the ACCESS DENIED event.