gpt4 book ai didi

c# - 第二次重命名目录锁重命名的目录我要重命名

转载 作者:行者123 更新时间:2023-11-30 19:07:28 25 4
gpt4 key购买 nike

我在多次重命名目录时遇到问题,它似乎锁定了文件。

// e comes from a objectListView item
DirectoryInfo di = (DirectoryInfo)e.RowObject;
DirectoryInfo parent = Directory.GetParent(di.FullName);
String newPath = Path.Combine(parent.FullName, e.NewValue.ToString());

// rename to some temp name, to help change lower and uppercast names
di.MoveTo(newPath + "__renameTemp__");
di.MoveTo(newPath);

// Trying to cleanup to prevent directory locking, doesn't work...
di = null;
parent = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

非常感谢任何帮助,因为第一次重命名工作正常,但是当尝试对重命名的文件夹进行新的重命名时,它会抛出异常:

The process cannot access the file because it is being used by another process. A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll

所以第一次重命名该文件夹有效,第二次抛出异常,我猜应用程序锁定了新文件夹,但如何解决它?我应该能够重命名一个文件夹两次,对吧?

最佳答案

简介

为了重现您的问题,我创建了以下方法:

private static string RenameFolder(string path, string newFolderName)
{
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo parent = Directory.GetParent(di.FullName);
String newPath = Path.Combine(parent.FullName, newFolderName);

// rename to some temp name, to help change lower and uppercast names
di.MoveTo(newPath + "__renameTemp__");
di.MoveTo(newPath);

return di.FullName;
}

当我像下面这样调用它时,它起作用了:

var path = @"C:\Temp\test";
var newPath = RenameFolder(path, "TESt");
newPath = RenameFolder(path, "Test1");

当我像下面这样调用它时,它不起作用:

var path = @"C:\Temp\test";
var newPath = RenameFolder(path, "TESt");
newPath = RenameFolder(newPath, "Test1");

这两个调用之间的唯一区别是,在第一个版本中,我传入了原始名称,即所有内容都是小写的。在第二种情况下,我提供了新名称,即除了最后一个字母以外的所有内容都是大写的。即使在两次调用 RenameFolder 之间休眠 20 秒也不会改变这一点。奇怪!

解决方案

如果我像这样实现 RenameFolder它在两种情况下都有效:

private static string RenameFolder(string path, string newFolderName)
{
String newPath = Path.Combine(Path.GetDirectoryName(path), newFolderName);

// rename to some temp name, to help change lower and uppercast names
Directory.Move(path, newPath + "__renameTemp__");
Directory.Move(newPath + "__renameTemp__", newPath);

return newPath;
}

不知何故,DirectoryInfo 似乎在路径上有一个区分大小写的锁。

解释
我没有,也许对 DirectoryInfo 的内部方式有更多了解的人可以阐明这种奇怪的行为。

重点
如果您不知道自己在做什么,请不要使用 GC.Collect!通常,您不需要调用此方法。

关于c# - 第二次重命名目录锁重命名的目录我要重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com