C# UnauthorizedAccessException 试图删除文件夹中的文件,我可以在其中删除具有相同代码的其他文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1157246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:35:21  来源:igfitidea点击:

UnauthorizedAccessException trying to delete a file in a folder where I can delete others files with the same code

c#exceptionio

提问by eKek0

I'm getting a Unauthorized Access Exception

我收到未经授权的访问异常

  • in a file which I can delete manually.
  • in a folder where I'm able to delete by code other files
  • and the file isn't marked as read only
  • besides, I'm using Windows XP in a standalone PC and I have not assigned any permissions to the folder or the file.
  • no other process is using the file
  • 在我可以手动删除的文件中。
  • 在我可以通过代码删除其他文件的文件夹中
  • 并且该文件未标记为只读
  • 此外,我在一台独立的 PC 上使用 Windows XP,我没有为文件夹或文件分配任何权限。
  • 没有其他进程正在使用该文件

If it helps, this is the code where the exception ocurrs:

如果有帮助,这是发生异常的代码:

protected void DeleteImage(string imageName)
{
    if (imageName != null)
    {
        string f = String.Format("~/Images/{0}", imageName);
        f = System.Web.Hosting.HostingEnvironment.MapPath(f);
        if (File.Exists(f))
        {
            if (f != null) File.Delete(f);
        }
    }
}

Why could this happen?

为什么会发生这种情况?

回答by jpoh

If it's not read-only it's possible that it is currently in use by another process.

如果它不是只读的,则它可能当前正被另一个进程使用。

回答by Bill Crim

You, the human user, have a login with certain rights. The Web server might have a different login with different rights. A user starting with IUSR_XXXX or some such thing. Make sure that user has rights to the directory.

您,人类用户,拥有具有特定权限的登录名。Web 服务器可能具有不同权限的不同登录名。以 IUSR_XXXX 或类似内容开头的用户。确保用户有权访问该目录。

Without more info on the context in which you are deleting the file, I assume that the Web server user has different rights to a file than you do.

如果没有关于删除文件的上下文的更多信息,我假设 Web 服务器用户对文件的权限与您不同。

回答by Jimmy Chandra

Checking the obvious first...

首先检查明显的...

When you open the file property and take a look at its security settings. Does the user running the code (i.e. if this is ASP.NET, Network Services / Domain Service Account) has access to actually delete the file?If it is not, then change it and try again.

当您打开文件属性并查看其安全设置时。运行代码的用户(即,如果这是 ASP.NET,网络服务/域服务帐户)是否有权实际删除文件?如果不是,请更改它并重试。

Are you running as administrator when trying to delete this manually?If you are, then that's probably why you are able to delete it manually. Try deleting it as the account running your ASP.NET (I'm assuming it is ASP.NET since you are using System.Web.Hosting.HostingEnvironment.MapPath.)

尝试手动删除时,您是否以管理员身份运行?如果是,那么这可能就是您可以手动删除它的原因。尝试将其作为运行 ASP.NET 的帐户删除(我假设它是 ASP.NET,因为您使用的是 System.Web.Hosting.HostingEnvironment.MapPath。)

If both failed, try to see if any other process is actually currently using this file. Good tool to find out is SysInternalProcess Monitor. Filter it by path containing your filename and you should see if anything is using it. Terminate the process and try again.

如果两者都失败,请尝试查看当前是否有任何其他进程正在使用此文件。查找的好工具是SysInternalProcess Monitor。通过包含您的文件名的路径过滤它,您应该查看是否有任何东西正在使用它。终止进程并重试。

回答by Brad Parks

I encountered the same problem, and found that writing my own Directory.Delete wrapper fixed it up. This is recursive by default:

我遇到了同样的问题,发现编写我自己的 Directory.Delete 包装器修复了它。默认情况下这是递归的:

using System.IO;

public void DeleteDirectory(string targetDir)
{
    File.SetAttributes(targetDir, FileAttributes.Normal);

    string[] files = Directory.GetFiles(targetDir);
    string[] dirs = Directory.GetDirectories(targetDir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

    foreach (string dir in dirs)
    {
        DeleteDirectory(dir);
    }

    Directory.Delete(targetDir, false);
}

回答by Piyush Soni

If the directory contains a read only file, it won't delete that using Directory.Delete. It's a silly implementation by MS.

如果目录包含只读文件,则不会使用 Directory.Delete 删除该文件。这是 MS 的愚蠢实现。

I am surprised no one suggested this method on the internet, which deletes the directory without recursing through it and changing every file's attributes. Here's that:

我很惊讶没有人在互联网上建议这种方法,它删除目录而不递归遍历它并更改每个文件的属性。这是:

Process.Start("cmd.exe", "/c " + @"rmdir /s/q C:\Test\TestDirectoryContainingReadOnlyFiles"); 

(Change a bit to not to fire a cmd window momentarily, which is available all over the internet)

(稍微更改为不立即触发 cmd 窗口,该窗口在 Internet 上随处可见)

回答by Priyabrata biswal

I too faced the Same Problem but eventually came up with a Generic Approach. Below are my codes.

我也面临同样的问题,但最终想出了一个通用方法。下面是我的代码。

String pathfile = "C:\Users\Public\Documents\Filepath.txt" ;

String pathfile = "C:\Users\Public\Documents\Filepath.txt" ;

            if (!Directory.Exists(pathfile))
            {
                File.SetAttributes(pathfile, FileAttributes.Normal);
                File.Delete(pathfile);
            }


                using (FileStream fs = File.Create(pathfile))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("What Ever Your Text is");

                    fs.Write(info, 0, info.Length);
                    File.SetAttributes(pathfile, FileAttributes.ReadOnly);

                }