C# - 重命名目录的方法

标签 c# directory rename ioexception

我正在使用Directory.Move(oldDir, newDir)重命名目录。我时不时地收到一个IOException说“访问路径‘oldDir’被拒绝”。但是,如果我右键单击资源管理器中的目录,我可以重命名它,没有任何问题。

所以我的问题是:是否有其他方法可以在不使用 Directory.Move 的情况下重命名目录?

我想过使用命令 shell ( Process.Start() ),但这应该是我这样做的最后一种方法。


更多详细信息

程序仍在运行,我收到异常,并且可以在 Windows 资源管理器中手动重命名它(右键单击 -> 重命名),同时我的光标暂停在 catch block 中的断点上。我还尝试在 Directory.Move 设置断点,成功在资源管理器中重命名目录(然后再次返回),跨过 Directory.Move并最终进入 catch (IOException)再次。

这是我的代码

public bool Copy()
{
    string destPathRelease = ThisUser.DestPath + "\\Release";

    if (Directory.Exists(destPathRelease))
    {
        try
        {
            string newPath = ThisUser.DestPath + '\\' + (string.IsNullOrEmpty(currBuildLabel) ? ("Release" + '_' + DateTime.Now.ToString("yyyyMMdd_HHmmss")) : currBranchName) + '.' + currBuildLabel;
            Directory.Move(destPathRelease, newPath);
        }   
        catch (IOException)
        {
           // Breakpoint
        }
    }
}

正如你所看到的,我刚刚进入了该方法。我以前从未接触过程序中的目录。

由于这种方法不适合我,所以我需要找到另一种方法。


解决方案

public bool Copy()
{
    string destPathRelease = ThisUser.DestPath + "\\Release";

    SHFILEOPSTRUCT struc = new SHFILEOPSTRUCT();

    struc.hNameMappings = IntPtr.Zero;
    struc.hwnd = IntPtr.Zero;
    struc.lpszProgressTitle = "Rename Release directory";
    struc.pFrom = destPathRelease + '\0';
    struc.pTo = ThisUser.DestPath + '\\' + (string.IsNullOrEmpty(this.currBuildLabel) ? ("Release" + '_' + DateTime.Now.ToString("yyyyMMdd_HHmmss")) : this.currBranchName) + '.' + this.currBuildLabel + '\0';
    struc.wFunc = FileFuncFlags.FO_RENAME;

    int ret = SHFileOperation(ref struc);
}

请注意,使用 pTo 很重要和pFrom作为零分隔双零终止的字符串。

最佳答案

您可以尝试使用 P/Invoke 来调用 SHFileOperation API(或 IFileOperation 接口(interface))。这就是 Explorer 理论上所使用的,因此它应该更直接地复制功能。

关于C# - 重命名目录的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560856/

相关文章:

python - 从同级目录导入

无法将正确的文件目录输出到带有 .cFileName 的链接列表

c# - C# 中 0 - 1000 之间的随机数生成器

c# - asp.net C# 中长时间运行的进程

sharepoint - 将 SharePoint 警报发送到 Exchange 中的公用文件夹

excel - 批量查找文件,复制文件,然后从 CSV 重命名文件

vb6 - 如何重命名 VB6 可执行文件?

c# - ServiceStack Redis获取结构始终返回默认值

c# - 如何重置 PipeReader 以便能够在 ASP.NET Core 中重新读取请求正文

java - 重命名目录中多个文件的脚本或java程序