Skip to main content
 首页 » 编程设计

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

2024年02月06日14yjmyzz

我正在尝试以编程方式删除损坏的符号链接(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)被删除时保持打开状态。如果您以前从未听说过,这可能是令人惊讶的行为。

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