简体   繁体   中英

How to list files/directories where there are symbolic links

I have a folder with symbolic links (cmd dir on that directory, lists these as SYMLINKD if that makes any difference). Any time I try to call Directory.GetFiles , Directory.GetDirectories() or any of the other variations in DirectoryInfo , I am given the following exception:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'SYMBOLIC_LINK_PATH'.

I have also tried these with the directory prefixed by \\?\ (the "long path prefix" as mentioned here: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation )

How do I walk the directory and delete these symbolic links? What alternatives do I have to walk the directory?

(As suggested in a comment, I have also tried Directory.GetFiles("DirectorytoSearch", "*", SearchOption.AllDirectories) with the same result: DirectoryNotFoundException even though the MSDN article notes that this option should "include reparse points such as.... symbolic links")

The article you mentioned:
https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation

Was posted on 09/15/2020, which is pretty recent.
Surely you've updated the .NET runtime you're using, right?

Also, as a minimum Windows 10 version 1607 is required, double check if you're updated.

When and if you're updating your runtime, check if the latest update for it was at least released after the 09/15/2020.

If you're using the .NET Framework runtime, try doing this in the .NET Core runtime, since it's updated more frequently.

If all else fails, try this solution: https://stackoverflow.com/a/53439677/2536887 ,
else submit a bug report.

Everyone's input helped me narrow down and figure out the problem. I believe the issue is that I had deleted the target of a symbolic link, but my recursive delete function still found it to be a directory. So when I tried to enumerate the files/directories of that symbolic link it threw a DirectoryNotFound exception (which is definitely confusing to encounter there because the directory still appears to exist - even in the file explorer, until you click on it).

The solution is that when trying to gather the children of a directory, catch DirectoryNotFound exceptions and try to delete the directory instead. That worked for me

        FileInfo[] files = null;
        try
        {
            files = currentDirectory.GetFiles("*", SearchOption.AllDirectories);
        }
        catch (DirectoryNotFoundException)
        {
            currentDirectory.Delete(true);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM