I'm writing a C# program that uses System.IO methods to work with files and directories. Some of these methods include Directory.GetDirectories, Directory.GetFiles, and Path.GetDirectoryName which can all throw the PathTooLongException exception if the path is too long. My first question is does the Microsoft .NET Framework enforce the maximum length of a path, the same way that a call to a Windows API in C++ does? Does a path (in a string) in C# that exceeds MAX_PATH cause PathTooLongException to be thrown?
Should I use this?
string getFolderName(string path)
{
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
if (path.Length > 260)
{
System.Diagnostics.Debug.WriteLine("Path is too long.");
return string.Empty;
}
string folderName = System.IO.Path.GetDirectoryName(path);
return folderName;
}
Or this?
string getFolderName(string path)
{
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
string folderName = string.Empty;
try {
folderName = System.IO.Path.GetDirectoryName(path);
}
catch (System.IO.PathTooLongException)
{
System.Diagnostics.Debug.WriteLine("Path is too long.");
}
return folderName;
}