当文件存在时,我需要向用户显示一些消息,显示消息“文件存在...你要覆盖它吗?”
if (File.Exists(binaryFilePath))
{
Program.DisplayMessage("The file: " + binaryFileName + " exist. You want to overwrite it? Y/N");
string overwrite = Console.ReadLine();
while (overwrite != null)
{
if (overwrite.ToUpper() == "Y")
{
WriteBinaryFile(frameCodes, binaryFilePath);
} if (overwrite.ToUpper() == "N")
{
throw new IOException();
overwrite = null;
} if (overwrite.ToUpper() != "Y" && overwrite.ToUpper() != "N")
{
Program.DisplayMessage("!!Please Select a Valid Option!!");
overwrite = Console.ReadLine();
}
}
}
如果用户写“Y”过程开始并完成正常...问题是如何停止? 我试着用这个,但没有工作......
我该怎么做?
答案 0 :(得分:3)
if (File.Exists(binaryFilePath))
{
while (true)
{
Program.DisplayMessage("The file: " + binaryFileName + " already exist. Do you want to overwrite it? Y/N");
string overwrite = Console.ReadLine();
if (overwrite.ToUpper().Equals("Y"))
{
WriteBinaryFile(frameCodes, binaryFilePath);
break;
}
else if (overwrite.ToUpper().Equals("N"))
{
Console.WriteLine("Aborted by user.");
break;
}
else
{
Program.DisplayMessage("!!Please Select a Valid Option!!");
overwrite = Console.ReadLine();
continue; // not needed - for educational use only ;)
}
}
}
试试并学习基础知识(条件,循环,英语......)。然后你可以回来询问为什么在你的情况下抛出异常(特别是那个);)
答案 1 :(得分:0)
尝试使用break;
打破循环(也使用if-else-if而不是if-if ..)
if (File.Exists(binaryFilePath))
{
while (true)
{
Program.DisplayMessage("The file: " + binaryFileName + " exist. You want to overwrite it? Y/N");
string overwrite = Console.ReadLine();
if (overwrite.ToUpper() == "Y")
{
WriteBinaryFile(frameCodes, binaryFilePath);
break;
}
else if (overwrite.ToUpper() == "N")
{
throw new IOException();
overwrite = null;
break;
}
else if (overwrite.ToUpper() != "Y" && overwrite.ToUpper() != "N")
{
Program.DisplayMessage("!!Please Select a Valid Option!!");
overwrite = Console.ReadLine();
}
}
}
虽然“N”之后的break;
没用,但我希望你能处理你扔到别处的异常。
答案 2 :(得分:0)
我相信,用户选择阅读应该委托给另一种方法。像这样:
static void Main(string[] args)
{
//...
if (File.Exists(binaryFilePath))
{
if(ReadBool("The file: " + binaryFileName + " exist. You want to overwrite it? Y/N"))
WriteBinaryFile(frameCodes, binaryFilePath);
else
throw new IOException();
}
}
static bool ReadBool(String question)
{
while (true)
{
Console.WriteLine(question);
String r = (Console.ReadLine() ?? "").ToLower();
if (r == "y")
return true;
if (r == "n")
return false;
Console.WriteLine("!!Please Select a Valid Option!!");
}
}