其他分享
首页 > 其他分享> > 拒绝访问路径

拒绝访问路径

作者:互联网

好吧,我已经看到了很多有关此问题的问题,但仍然没有人回答我的问题.实际上,我看到的每个问题都互不相同,这种访问方式似乎确实困扰着程序员.

请检查代码:

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

堆栈跟踪:

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

当然,我尝试了通常的方法:

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

但这并没有改变!

我还尝试通过右键单击dir1->手动更改权限.属性->安全->编辑->添加->键入所有人(在输入对象名称中进行选择)->好的->完全控制所有人. (我还看到我的用户帐户也具有完全控制权)

任何提示将不胜感激

解决方法:

虽然它是“访问被拒绝”异常,但听起来像文本文件正在使用中并且无法移动,因为存在对该文件的开放引用.

File.Create方法返回一个FileStream对象,我认为在修改文件之前,必须关闭/处理该对象.

为您的内部循环尝试以下操作:

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

标签:access-denied,directory-permissions,c
来源: https://codeday.me/bug/20191101/1979992.html