【发布时间】:2017-01-23 17:28:09
【问题描述】:
这个函数应该在它作为参数的路径中找到最长的文件。
它似乎运作良好,问题是我不确定如何处理异常。
在 PathTooLongException 的情况下,我想将 _MaxPath 设置为 -2 并退出函数,如果出现其他异常,将其设置为 -1 并退出函数,否则将其设置为最长的文件路径。
我不确定在这种情况下处理异常的正确方法是什么。
可能是一个愚蠢的问题,但我是 C# 新手...
static int _MaxPath = 0;
public static void GetLongestFilePath(string p)
{
try
{
foreach (string d in Directory.GetDirectories(p))
{
foreach (string f in Directory.GetFiles(d))
{
if (f.Length > _MaxPath)
{
_MaxPath = f.Length;
}
}
GetLongestFilePath(d);
}
}
catch (Exception e)
{
if (e is PathTooLongException)
{
_MaxPath = -1;
}
}
finally
{
System.Environment.Exit(-99);
}
}
【问题讨论】:
-
为什么将结果存储在静态字段中?那不方便。还有一个名称以
Get开头的方法应该返回一些东西,它不应该是无效的。
标签: c# exception-handling try-catch