Reputation: 3421
I need to show some message to user when a file exist, that display the message "the files exist... do you want to overwrite it??"
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();
}
}
}
if the user write "Y" the process start and done normal... the problem is how can stops?? I try with this while, but not work...
How can I do this?
Upvotes: 2
Views: 10314
Reputation: 11808
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 ;)
}
}
}
Try that and go learn your basics (conditions, loops, english, ...). Then you can come back and ask why throwing an exception (particularly that one) is wrong in your case ;)
Upvotes: 3
Reputation: 22137
I believe, user choice reading should be delegate to another method. Like this:
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!!");
}
}
Upvotes: 0
Reputation: 108937
Try using break;
to break out of the loop (also use if-else-if rather than 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();
}
}
}
although the break;
after "N" is useless but I hope you are handling the exception that you are throwing elsewhere.
Upvotes: 0