I am using DirectoryInfo and FileInfo in .Net 4.0 to enumerate files in a directory tree and I am hitting PathTooLongException. Simplified version is below
public static class Test
{
public static void Search(DirectoryInfo base)
{
foreach(var file in base.GetFiles())
{
try
{
Console.WriteLine(file.FullName);
} catch(PathTooLongException ex)
{
// What path was this?
}
}
foreach(var dir in base.GetDirectories())
{
Search(dir);
}
}
}
When the error is thrown, I want to know what file path caused the problem. Obviously I can't ask for FullName
as that is what errored. I can get name from file.Name
, but if I can't get the rest of the path as file.Directory
gives a PathTooLongException
even though the DirectoryInfo
that the file was found from worked fine! (I can't use that though as the actual code is much more complex).
Looking through the stack trace it seems that it's using an internal path (I see a protected file.FullPath
from debug), and trying to tear the directory from the full (oversized) path. Most of the problems seem to involve System.IO.Path.NormalizePath
, with I hear went through a few changes in .Net 4.0. I have not tried on previous versions of the framework.
My questions:
- How can I get the full path from this exception; it is seemingly passed without any useful information.
- Why would the framework need to limit characters in a path to chop off the filename?
Thanks in advance for any help,
Andy