我有一个try catch块,当它捕获异常时我希望它返回ReadLine(),以便用户可以再次尝试输入有效的选择
Console.Write("CSV File: ");
string csvFile = Console.ReadLine();
try
{
List<DictionaryLabels> values = csvRead(csvFile);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("CSV File not found \nPress any key to contiune");
Console.ReadLine();
}
答案 0 :(得分:1)
您对该问题的解决方案可能有效,但它不遵循编程的概念。只要情况出现意外而不是&#34;可能会发生&#34;应该使用Try-catch块。场景。
下面的代码描述了处理此问题的一种方法:您将从用户获得第一个输入&amp;验证,如果文件存在。确认后,您可以尝试打开它。如果失败(例如文件不包含CSV格式的文本),则应抛出异常。
如果while( condition )
中的条件不是假的(!File.Exists()),循环将一次又一次地运行。
using System.IO;
Console.Write("Please enter the path for file:");
string lPath = Console.ReadLine();
while(!File.Exists(lPath))
{
Console.Write("File has not been found. Please enter new path:");
lPath = Console.ReadLine();
}
try
{
List<DictionaryLabels> values = csvRead(lPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
答案 1 :(得分:0)
Rational
你在try结束时将valid设置为true并从catch中删除readline(感谢Quantic指出我的遗漏)。
答案 2 :(得分:0)
Console.Write("CSV full path File: ");
string csvFile = Console.ReadLine();
while (!ValidateCsv(csvFile))
{
Console.Write("Retype full path CSV File: ");
csvFile = Console.ReadLine();
}
private static bool ValidateCsv(string csvFile)
{
bool isPathTrue = false;
FileInfo csvFileInfo = new FileInfo(csvFile);
isPathTrue = csvFileInfo.Exists;
return isPathTrue;
}