使用C#捕获文件异常

时间:2019-01-21 15:29:18

标签: c# visual-studio exception-handling

以下是我今天使用Visual Studios Console App进行的工作。

我要发生的事情(当前不是这样)是在控制台应用程序打开时,我键入第一个“ 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");

1 个答案:

答案 0 :(得分:2)

由于您需要不断问一个问题,直到用户正确为止,因此需要一个循环。接下来,您需要检查该路径是否存在。

            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();
                }
            }