【问题标题】:Catching File Exceptions using c#使用 c# 捕获文件异常
【发布时间】:2019-01-21 15:29:18
【问题描述】:

以下是我今天使用 Visual Studios 控制台应用程序正在努力解决的问题。

我想要发生的事情,目前不是,是当控制台应用程序打开时,我输入第一个“checksPath”,如果结果不存在,我希望它说路径错误,或者让用户再试一次,或者关闭应用程序。如果路径有效,则移动到下一个“reportDest”,同样适用。如果它是无效路径,我想要一条消息这样说,可以选择重试或关闭应用程序。如果输入的两个路径(最终)都有效,我想要一条消息说现在将生成报告。生成报告的脚本的其余部分非常好,只是我放在下面的那一点很麻烦。

            string checksPath;
        Console.Write("Please enter the source path for the Checks Workbook, including the name of the file (Not including the file extension): ");
        checksPath = Console.ReadLine() + ".xlsx";

        try
        {
            if (File.Exists("checksPath"))
                throw new FileNotFoundException();
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("Invalid path - Please close the app and try again!");
            Console.ReadLine();
        }



            string reportDest;
            Console.Write("Please enter the folder location and file you wish your report to go to (Not including the file extension): ");
            reportDest = Console.ReadLine() + ".xlsx";

        try
        {
            if (File.Exists("reportDest"))
                throw new FileNotFoundException();
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("Invalid path - Please close the app and try again!");
            Console.ReadLine();
        }



        Console.WriteLine("Your report will now produce");

【问题讨论】:

  • 异常处理适用于异常情况。在这种情况下,您应该使用if/else来处理预期条件。
  • if (!File.Exists("checksPath"))怎么样

标签: c# visual-studio exception-handling


【解决方案1】:

由于您需要不断地提出问题,直到用户回答正确,您将需要一个循环。接下来在该循环中,您需要检查路径是否存在。

            bool run = true;

            while (run)
            {
                Console.Clear();
                Console.WriteLine("Enter Path:");
                string answer = Console.ReadLine();

                if (Directory.Exists(answer)) run = false;
                else
                {
                    Console.WriteLine("Path Does not exists. Try again. Press enter to continue...");
                    Console.ReadLine();
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多