C# - Ways to rename a directory [duplicate]

痴心易碎 提交于 2019-12-11 07:24:21

问题


I'm using Directory.Move(oldDir, newDir) to rename a directory. Every now and then I get an IOException saying "Access to the path 'oldDir' is denied". However if I right click the directory in the explorer I can rename it without any issues.

So my question is: Are there any other ways to rename a directory without using Directory.Move?

I thought of using the command shell (Process.Start()) but this should be my last way of doing it.


Further details

The program is still running, I get the exception and can rename it manually in windows explorer (right click -> rename) while my cursor is paused on the breakpoint in the catch block. I also tried setting a breakpoint at Directory.Move, successfully renamed the directory in explorer (and back again), stepped over Directory.Move and ended up in the catch (IOException) again.

Here is my code

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
        }
    }
}

As you can see I just entered the method. I never touched the directory in my program before.

Since this way is not working for me I need to find another way to do so.


Solution

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

Please note it's important to use pTo and pFrom as zero delimited double zero terminated strings.


回答1:


You could try using P/Invoke to call the SHFileOperation API (or the IFileOperation interface). This is what Explorer uses in theory, so it should replicate the functionality more directly.




回答2:


Try using DirectoryInfo.MoveTo() instead of Directory.Move().

Also, check this old SO question: it doesn't seems to have the same exception you're figuring out, but you can find some good advice.



来源:https://stackoverflow.com/questions/16560856/c-sharp-ways-to-rename-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!