gpt4 book ai didi

c# - File.Delete() 在程序完成之前不删除文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:02 24 4
gpt4 key购买 nike

我正在尝试以编程方式删除损坏的符号链接(symbolic link),并将其替换为具有同名有效目标的符号链接(symbolic link)。然而,当 CreateSymbolicLink() 执行时,File.Delete() 仍然没有真正删除文件(我已经验证文件在 File.Delete() 执行后仍然存在,没有错误或警告)。

当程序完成执行时,文件才真正被删除。有没有搞错?这会阻止创建符号链接(symbolic link)。有什么想法吗?

    private static string replaceSymbolicLink(string linkPath, string newTargetPath)
{
Boolean linkIsFile = File.Exists(linkPath);
Boolean linkIsDir = Directory.Exists(linkPath);

// Create a replacement of the same name and link type with the new target
string newTargetPathDOS = getAbsPathFromPath(newTargetPath);
Boolean targetIsFile = File.Exists(newTargetPathDOS);
Boolean targetIsDir = Directory.Exists(newTargetPathDOS);
if (targetIsFile || targetIsDir)
{
if (linkIsFile)
{
File.Delete(linkPath);
Console.WriteLine(File.Exists(linkPath));
}
else
{
Directory.Delete(linkPath);
}
SymbolicLink type;
if (targetIsFile)
{
type = SymbolicLink.File;
}
else
{
type = SymbolicLink.Directory;
}
CreateSymbolicLink(linkPath, newTargetPath, type);
return getGuidFromPath(linkPath);
}
return null;
}

最佳答案

在 Windows 上删除不是立即的。文件被标记为已删除,并且在关闭最后一个句柄时实际上消失了。通常,此机制是不可见的,因为大多数文件都是使用防止删除的共享权限打开的。这会导致删除失败或立即完成。

FileShare.Delete 允许在文件(FileStream)被删除时保持打开状态。如果您以前从未听说过,这可能是令人惊讶的行为。

所以你可能有文件仍然打开或其他一些进程已经打开。

关于c# - File.Delete() 在程序完成之前不删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29332211/

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