简体   繁体   English

作为过程启动后写入文件会导致UnauthorizedAccessException(拒绝访问路径XXX。)

[英]Write to a file after it is started as a process causes UnauthorizedAccessException (Access to the path XXX is denied.)

The following C# code fails at line "File.WriteAllText("test_a.cmd", "timeout 15")" sometimes, anyone who knows why and how to solve it? 以下C#代码有时在“ File.WriteAllText(“ test_a.cmd”,“超时15”)“行中失败,任何人都知道为什么以及如何解决它? Thanks. 谢谢。

        for (int i = 0; i < 100; i++)
        {
            File.WriteAllText("test_a.cmd", "rem timeout 1");
            var p = Process.Start("test_a.cmd");

            p.WaitForExit();
            p.Dispose();
            p = null;

            //GC.Collect();
            //GC.WaitForPendingFinalizers();

            File.Delete("test_a.cmd");

            // Somtetimes it causes System.UnauthorizedAccessException: Access to the path 'XXX\test_a.cmd' is denied.
            File.WriteAllText("test_a.cmd", "timeout 15");
        }

There's another process that has the file opened with delete sharing. 另一个过程是使用删除共享打开文件。 Which allows your File.Delete() call to succeed. 这将使您的File.Delete()调用成功。 But not the subsequent File.WriteAllText(). 但不包含后续的File.WriteAllText()。 Because the file still exists after you deleted it. 因为删除后文件仍然存在。 It will not disappear until the other process has closed its handle on the file. 在其他进程关闭其文件句柄之前,它不会消失。 Any attempt to overwrite the file while it is still in limbo like this will fail with an "access denied" error. 当文件仍处于混乱状态时,任何尝试覆盖文件的尝试都将失败,并显示“拒绝访问”错误。

Such are the vagaries of running a program on a multi-tasking operating system where other processes may be interested in the files that you manipulate. 这是在多任务操作系统上运行程序的变幻莫测的程序,其中其他进程可能会对您操作的文件感兴趣。 There's always a good candidate for such a process on most any Windows install, disable your anti-virus program to see if that solves the problem. 在大多数Windows安装中,这样的过程始终是个不错的选择,请禁用防病毒程序以查看是否可以解决问题。

Beyond just sleeping for a while and trying again, there's a decent way to minimize the lossage. 除了只睡一会儿然后再试一次,还有一种体面的方法可以最大程度地减少损失。 You can rename the file, much lower odds that you'll be hit with this exception: 您可以重命名该文件,但发生此异常的几率会大大降低:

File.Delete("test_a.cmd.bak");
File.Move("test_a.cmd", "test_a.cmd.bak");
for (int attempt = 0; ; ++attempt) {
    try {
       File.WriteAllText("test_a.cmd", "timeout 15");
       break;
    }
    catch (System.UnauthorizedAccessException ex) {
       if (attempt > 10) throw;
       System.Threading.Thread.Sleep(1000);
    }
}
try {
    File.Delete("test_a.cmd.bak");
}
catch (Exception ex) {}

Since File.WriteAllText() creates/overwrites a file, the call to Delete is not needed. 由于File.WriteAllText()创建/覆盖文件,因此不需要调用Delete。 In fact, that is what, probably, causes your issue. 实际上,这可能是导致您出现问题的原因。

So, my solution is to: 因此,我的解决方案是:

  • Remote File.Delete 远程文件删除
  • Add Thread.Sleep(100) before last WriteAllText 在最后的WriteAllText之前添加Thread.Sleep(100)

The sleep part is to allow Windows to do processing and that is what basically causes your exception. 睡眠部分是允许Windows执行处理,而这基本上是导致您异常的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 File.ReadAllText(): System.UnauthorizedAccessException: '访问路径被拒绝。' - File.ReadAllText(): System.UnauthorizedAccessException: 'Access to the path is denied.' C# 对路径的访问被拒绝...(System.UnauthorizedAccessException:对路径'C:\'的访问被拒绝。) - C# access to the path is denied…(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.) 对路径的访问被拒绝。 - Access to the path is denied. UnauthorizedAccessException:对路径的访问被拒绝 - UnauthorizedAccessException: Access to the path is denied UnauthorizedAccessException:拒绝访问路径 - UnauthorizedAccessException: Access to path denied UnauthorizedAccessException-拒绝访问路径 - UnauthorizedAccessException - Access to the path is denied 创建新目录将返回错误:“ System.UnauthorizedAccessException:&#39;对路径&#39;C:\\ Users&#39;的访问被拒绝。 - Creating new directory returns error :"System.UnauthorizedAccessException : 'Access to the path 'C:\Users' is denied.' 拒绝访问“ somepath”路径。” - Access to the path “somepath” is denied." UnauthorizedAccessException:Winform拒绝访问路径 - UnauthorizedAccessException: Access to the path is denied winform C#-UWP-System.UnauthorizedAccessException:“访问被拒绝”。 - C# - UWP - System.UnauthorizedAccessException: 'Access is denied.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM