使用实例替换文件用户菜单

本文关键字:用户 菜单 文件 替换 实例 | 更新日期: 2023-09-27 17:53:20

我有一个从目录写入文件的应用程序。该软件只能读取一个或多个文件,例如:

Case 1:  "file_1.dat"
Case 2: "file_1.dat", "file_2.dat", "file_3.dat"...etc

如果文件存在于目录中,则显示此消息。我遇到的问题是,如果用户写入"N",程序需要继续读取其他文件,我不知道如果用户写入"N",如何继续询问相同的问题而不取消进程。我需要程序继续相同的过程,正常检查其他文件是否存在。那我该怎么办呢?

if (File.Exists(binaryFilePath))
            {
                Program.DisplayUserOptionMessage("The file: " + binaryFileName + " exist. You want to overwrite it? Y/N");
                //string overwrite = Console.ReadLine();
                 while (true)
                 {
                    string overwrite = Console.ReadLine();
                    if (overwrite.ToUpper() == "Y")
                    {
                       WriteBinaryFile(frameCodes, binaryFilePath);
                       break;
                    } 
                    else if (overwrite.ToUpper() == "N")
                    {
                        //Program.DisplayExceptionMessage("apply this for all the rest?? ");
                        throw new IOException();                        
                    } 
                    else
                    {
                    Program.DisplayUserOptionMessage("!!Please Select a Valid Option!!");
                    overwrite = Console.ReadLine();
                    continue;
                    } 
                }
            }

使用实例替换文件用户菜单

看起来您拥有的代码片段是由处理文件的循环调用的。我可以想象你扔的IOException会把你踢出那个循环……不确定为什么需要这样做,因为它不是一个真正的异常?

最好的办法是在处理文件的循环中捕获这个异常,处理它(写入日志,或者继续),然后继续循环中的下一个项。

另一种选择是简单地'返回'而不是抛出IOException

我认为你还有一个小故障,如果用户输入一个无效的值,你会提示他两次输入一个有效的值。将overwrite = Console.ReadLine();放入else{...}回路…在下一次循环开始时调用

我认为你不需要while (true)循环。而是while (!isFileProcessed)(稍后会详细介绍)。我假设您正在遍历输入文件名,如果是这样,则可以询问"文件存在"。你想重写它吗?Y/N"每个文件的问题。

然而,你的程序可能需要不同的结构:

string[] filesNames = new[] { "file_1.dat", "file_2.dat", "file_3.dat" };
foreach (var name in filesNames)
{  
    // ... 
    if (binaryExists)
    {
        bool isFileProcessed = false;
        Program.DisplayUserOptionMessage("The file: " + binaryFileName 
            + " exist. You want to overwrite it? Y/N");
        while (!isFileProcessed)
        {
            string overwrite = Console.ReadLine();
            if (overwrite.ToUpper() == "Y")
            {
                WriteBinaryFile(frameCodes, binaryFilePath);
                isFileProcessed = true; 
            }
            else if (overwrite.ToUpper() == "N")
            {
                isFileProcessed = true; 
            } 
            else
            {
                // here we do nothing with isFileProcessed flag: 
                // user still needs to select proper option, loop continues 
                Program.DisplayUserOptionMessage(
                    "!!Please Select a Valid Option!!");
            }
        } 
     }
 }