【问题标题】:Folder Rename using Directory.Move(): Access to Path is Denied使用 Directory.Move() 重命名文件夹:拒绝访问路径
【发布时间】:2021-10-04 18:26:09
【问题描述】:

使用目录重命名文件夹时,我有公共网络共享文件夹。移动():拒绝访问路径,实际问题是当文件夹被另一个系统或另一个进程打开时,如果有可能重命名文件夹或关闭另一个系统或另一个进程打开的文件夹

我的代码

static void moveToShare()
{
    if (!Directory.Exists("\\Share")) Directory.CreateDirectory("\\Share");
    string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
    try
    {
        Directory.Move("\\Output", "\\Share\\" + timestamp);
    }
    catch(Exception e)
    {
        Console.WriteLine("Cant Move Folder: " + e.Message);
    }
}

【问题讨论】:

  • 能等其他系统关闭吗?也许每隔一秒就会打开检查目录。
  • 因为如果其他系统打开它,你同时重命名它。可能有错误。

标签: c# exception directory access-denied


【解决方案1】:

您必须获得访问权限。

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsIdentity idnt = new WindowsIdentity(username, password);
WindowsImpersonationContext context = idnt.Impersonate();


if (!Directory.Exists("\\Share"))
   Directory.CreateDirectory("\\Share");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
        Directory.Move("\\Output", "\\Share\\" + timestamp);
}
catch(Exception e)
{
    Console.WriteLine("Cant Move Folder: " + e.Message);
}

context.Undo();

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 2020-12-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多