我在用着Directory.Move(oldDir, newDir)
重命名目录。我时不时地得到一个IOException
说“访问路径‘oldDir’被拒绝”。但是,如果我右键单击资源管理器中的目录,我可以重命名它,没有任何问题。
所以我的问题是:有没有其他方法可以重命名目录而不使用Directory.Move
?
我想到使用命令外壳(Process.Start()
)但这应该是我这样做的最后一种方式。
更多细节
该程序仍在运行,我收到异常,并且可以在 Windows 资源管理器中手动重命名它(右键单击 -> 重命名),同时我的光标暂停在 catch 块中的断点上。我也尝试在以下位置设置断点Directory.Move
,成功地在资源管理器中重命名了目录(并再次返回),跨过Directory.Move
并最终在catch (IOException)
again.
这是我的代码
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
}
}
}
正如你所看到的,我刚刚输入了该方法。我以前从未接触过程序中的目录。
由于这种方法不适合我,我需要找到另一种方法来做到这一点。
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);
}
请注意,使用它很重要pTo
and pFrom
作为零分隔双零终止的字符串。