简体   繁体   English

访问路径...被拒绝

[英]Access To The Path ... Is Denied

Alright, I've seen tons of questions about this thing, but still, no one answers my question.好吧,我已经看到很多关于这件事的问题,但仍然没有人回答我的问题。 In fact, each one of the questions I saw differs from the other, this access thing really seems to be hassling programmers.事实上,我看到的每一个问题都不尽相同,这个访问问题似乎真的在困扰程序员。

Please check out the code:请查看代码:

DirectoryInfo Dir1 = Directory.CreateDirectory(Desktop + "\\DIR1");
DirectoryInfo Dir2 = Directory.CreateDirectory(Desktop + "\\DIR2");
//* Lets Create a couple of SubDirs in DIR1
for (int i = 0; i < 5; i++)
{
  // this will create 5 SubDirs in DIR1, named Sub1, Sub2 ... Sub5.
  Dir1.CreateSubdirectory("Sub" + (i + 1).ToString()); 
  //* lets create 5 text files in each SubDir:
  for (int j = 0; j < 5; j++)
  {
    File.Create(Dir1.FullName + "\\Sub"+(i+1).ToString() + "\\text"+(j+1).ToString() + ".txt"); 
  }
}

//* Lets Move all what we created in DIR1 to DIR2 (THIS IS WHERE I'M GETTING THE EXCEPTION
Directory.Move(Dir1.FullName, Dir2.FullName + "\\DIR1");
// I also Tried Dir1.MoveTo(Dir2.FullName + "\\DIR1");

Stack Trace:堆栈跟踪:

at System.IO.DirectoryInfo.MoveTo(String destDirName)
at Directory_Class.Program.Main(String[] args) in c:\users\vexe\documents\visual studio 2010\Projects\Directory_Class\Directory_Class\Program.cs:line 207
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

And of course, I tried the usual:当然,我尝试了通常的做法:

DirectorySecurity DirSec = Dir1.GetAccessControl();
string user = Environment.UserName;
DirSec.ResetAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow));
Dir1.SetAccessControl(DirSec);

But it didn't change a bit但是一点都没变

I also tried changing the permissions manually, by right clicking dir1 -> properties -> security -> edit -> add -> typed everyone (in the enter object names to select) -> ok -> fullcontrol to everyone.我还尝试手动更改权限,方法是右键单击 dir1 -> 属性 -> 安全 -> 编辑 -> 添加 -> 键入每个人(在输入 object 名称中选择)-> 确定 -> 对所有人的完全控制。 (I also saw that my user account had full control as well) (我还看到我的用户帐户也拥有完全控制权)

Any hints would be deeply appreciated任何提示将不胜感激

While it is an Access Denied exception, it sounds like the text files are in use and cannot be moved because there are open references to the file.虽然这是一个拒绝访问异常,但听起来文本文件正在使用中并且无法移动,因为存在对该文件的打开引用。

The File.Create method returns a FileStream object which I'd imagine must be closed/disposed before the files can be modified. File.Create方法返回一个 FileStream object,我想在修改文件之前必须关闭/处置它。

Try the following for your inner loop:为您的内部循环尝试以下操作:

  for (int j = 0; j < 5; j++)
  {
    using(var fs = File.Create(Dir1.FullName + "\\Sub"+(i+1).ToString() + "\\text"+(j+1).ToString() + ".txt"))
    {
        //fs.WriteByte(...);
        fs.Close();
    }
  }

First off, you should use Path.Combine instead of doing string concatenation.首先,您应该使用 Path.Combine 而不是进行字符串连接。
Second off, the stack trace isn't as helpful as the exception being thrown.其次,堆栈跟踪不如抛出的异常有用。

I imagine your problem might be fixed by doing this though:我想你的问题可以通过这样做来解决:

Directory.Move(Dir1.FullName, Dir2.FullName);

If that fixes it, then the issue is with the DIR1 subdirectory you're trying to move it to.如果这样可以解决问题,那么问题出在您尝试将其移动到的 DIR1 子目录中。

As a debugging, step you should set failure auditing on the two folders (under advanced security settings).作为调试,您应该在两个文件夹上设置故障审核(在高级安全设置下)。 Just set everyone to audit all failures, then try your operation again.只需设置每个人都审核所有故障,然后再次尝试您的操作。 Depending on the OS version that you are running you should get the user account being used for the operation and what privilege was missing.根据您正在运行的操作系统版本,您应该获取用于操作的用户帐户以及缺少的权限。 Also make sure that there are no deny permissions set on the folder as they override all other permissions.还要确保没有在文件夹上设置拒绝权限,因为它们会覆盖所有其他权限。 You will want to look at the security event log.您将需要查看安全事件日志。 If there are no failure audits for the operation then it is not a permissions issues.如果操作没有失败审核,则不是权限问题。

It seems to me Windows loves blocking deletes (renames) of directories for literally no reason.在我看来,Windows 喜欢无缘无故地阻止目录的删除(重命名)。 I'm sure it has one, but I don't care what it is.我确定它有一个,但我不在乎它是什么。 I've found that deleting the contents of the directory, then deleting the empty folder works every time.我发现删除目录的内容,然后删除空文件夹每次都有效。 It works with the following rename as well.它也适用于以下重命名。

I came up with this, as windows was giving me access to path denied for the FROM directory.我想出了这个,因为 windows 让我可以访问 FROM 目录拒绝的路径。 I was just renaming it within the app, not really moving locations.我只是在应用程序中重命名它,而不是真正移动位置。 Anyway, based on the above information, I came up with this and it works.无论如何,基于上述信息,我想出了这个并且它有效。

public static void MoveTo_BruteItAsNecessary(this DirectoryInfo FROM, string TO, bool recycle = false)
{
    try
    {
        FROM.MoveTo(TO);
    }
    catch (IOException ex)
    {
        if (ex.Contains($"Access to the path '{FROM.FullName}' is denied."))
        {   // Contains checks the Message & InnerException.Message(s) recursively
            System.IO.Directory.CreateDirectory(TO);
            foreach (var dir in FROM.GetDirectories())
                dir.MoveTo(Path.Combine(TO, dir.Name));
            foreach (var file in FROM.GetFiles())
                file.MoveTo(Path.Combine(TO, file.Name));
            if (recycle)
                FROM.Recycle();
            else
                FROM.Delete();
        }
        else
            throw;
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM