我做了一个简单的程序。我想为try
,catch
语句添加循环,所以如果用户写入输入,他会得到错误消息并且程序让他再次写入。
Console.WriteLine("Enter The File Location");
string userValue = Console.ReadLine();
try
{
string content = File.ReadAllText(userValue);
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine(ex.Message);
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine("Could not find the Directory");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
答案 0 :(得分:1)
当您能够检查无效输入时,通常最好这样做,而不是让异常发生。 在您的情况下,您可以根据用户的输入检查File.Exists(...)和/或Directory.Exists(...)。 您可以将这些条件设置为循环语句,因此请继续提示用户,直到他们使用正确的目录和文件。 但是,我建议这不一定是最好的用户体验,因为您希望他们知道一个有效的文件和目录,他们可能不会。当然,你应该为他们提供退出循环的方法。
答案 1 :(得分:1)
您可以将代码包装在while
循环中,重复代码直到成功完成操作。
var success = false;
while (success == false)
{
Console.WriteLine("Enter The File Location");
string userValue = Console.ReadLine();
try
{
string content = File.ReadAllText(userValue);
Console.WriteLine(content);
success = true;
}
catch (FileNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine(ex.Message);
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine("Could not find the Directory");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
答案 2 :(得分:0)
当用户输入完成时(当您检测到Enter按键或具有完整的命令或其他情况时),我将使用具有指定条件的while构造。 然后你可以在不满足条件时循环(并且没有不可恢复的错误),并使用上面的代码检查用户错误并在需要时打印消息。
答案 3 :(得分:0)
你不需要循环。 Yuo可以使用递归函数。 试试这个:https://dotnetfiddle.net/4NR26P