【发布时间】:2014-06-28 15:07:02
【问题描述】:
我正在编写一个使用System.IO 方法处理文件和目录的C# 程序。其中一些方法包括Directory.GetDirectories、Directory.GetFiles 和Path.GetDirectoryName,如果路径太长,它们都会抛出PathTooLongException 异常。我的第一个问题是 Microsoft .NET Framework 是否强制执行路径的最大长度,与在 C++ 中调用 Windows API 的方式相同吗? C# 中超过MAX_PATH 的路径(在string 中)是否会导致PathTooLongException 被抛出?
我应该使用这个吗?
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;
}
还是这个?
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;
}
【问题讨论】:
-
你从哪里得到
MAX_PATH?捕获PathTooLongException几乎肯定会更可靠,因为它已包含在您调用的代码中。请注意,如果您不想处理异常,您甚至不需要 try/catch;让它传播给调用者。
标签: c# validation filesystems try-catch