我正在使用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/