Windows 服务自发失去对临时文件夹的访问权限

Windows service spontaneously losing access to temp folder

我有一个 Windows 服务应用程序,作为处理 MSMQ 消息的一部分,它写出到它所在帐户的 TEMP 目录中 运行。因此,如果服务在 MYDOMAIN\foo 下 运行,则 TEMP 目录将为 C:\Users\foo\AppData\Local\Temp\。相关代码为:

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);

这通常没有任何问题。在看似随机的时间间隔(有时一天几次,有时几天之间),该过程将在 File.WriteAllBytes 调用上开始失败。例外情况是:

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

重新启动服务可以解决所有问题,至少是暂时的。

磁盘space 没问题。 TEMP 文件夹的权限似乎很正常。除了上面的应用程序错误外,事件日志中没有任何有趣的内容。这是 运行 在 Windows Server 2012 R2 上。

堆栈跟踪:

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)

任何可能导致此问题的想法,或追踪问题可能出在哪里的提示?

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

在 运行 进程监视器并查看访问被拒绝事件的详细信息后,我能够看到这个。