Retrieve path information from PathTooLongException

人走茶凉 提交于 2019-12-05 19:28:32

I can't think of any other way off the top of my head other than using reflection, or using a library or P/Invoke to use the Windows APIs that support long paths and manually check length. The full path is stored in a protected string field called FullPath

foreach(var dir in new DirectoryInfo (@"D:\longpaths")
                     .GetFileSystemInfos("*.*", SearchOption.AllDirectories))
{
    try
    {
        Console.WriteLine(dir.FullName);
    }
    catch (PathTooLongException)
    {
                FieldInfo fld = typeof(FileSystemInfo).GetField(
                                        "FullPath", 
                                         BindingFlags.Instance | 
                                         BindingFlags.NonPublic);
                Console.WriteLine(fld.GetValue(dir));  // outputs your long path
    }
}

If you're trying to actually do something with the files and not just check file length, I would suggest using a library like this one from the BCL team at Microsoft, however it doesn't create DirectoryInfos, FileInfo or FileSystemInfo, only strings. So it's might not be a drop-in replacement for your code it seems.

As for the answer to your second question, I recommend reading this blog post dealing with long paths in .NET. This is a quote from it that explains why they haven't been quick to add long path support in .NET.

Very few people complain about a 32K limit, so, problem solved? Not quite. There are several reasons we were reluctant to add long paths in the past, and why we’re still careful about it, related to security, inconsistent support in the Windows APIs of the \?\ syntax, and app compatibility.

It's a 3 part series and explains a few reasons why the API is the way it is and why the limitation is there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!