完成流程后退出控制台应用程序

问题描述 投票:0回答:2

您好我的控制台应用程序用于下载html文件,然后将其发送到txt文件,在完成该过程后,我希望应用程序验证文件是否已创建,然后在告知用户该页面已下载后关闭程序。我想问一下如何验证文件是否存在,以及如何退出应用程序。

        Console.WriteLine("Enter a Valid Webpage URL such as http://wwww.google.com, this tool will download the HTML into a .txt file");
        string webPage = Console.ReadLine();
        Uri uriResult;
        bool result = Uri.TryCreate(webPage, UriKind.Absolute, out uriResult)
            && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
        WebClient client = new WebClient();
        //DownloadsWebpage
        string reply = client.DownloadString(webPage);

        Console.WriteLine(reply);
        //Location of file here
        Console.WriteLine("Please enter a valid address to save the .txt file such as C:\\Users\\Public\\String.txt, then press any button to exit");
        string txtDir = Console.ReadLine();
        File.WriteAllText(txtDir, reply);
        Console.ReadLine();
c# .net console-application
2个回答
1
投票

为了验证文件是否存在,有一个名为File.Exists()的方法可以告诉您它是否已创建。然后,一旦你的程序到达main的末尾,它将自动编辑。

你的File.WriteAllText(txtDir, reply);可能是以下类似的东西:

if (!File.Exists(txtDir)) {
    Console.WriteLine("Some error creating file");
}

当你想退出时,让你在到达main结束时编程关闭或使用Enviroment.Exit(0)


1
投票

要检查文件是否存在并退出:

if(System.IO.File.Exists(pathname))

{

 System.Environment.Exit(0);

}

//在这里做点其他事情来恢复

© www.soinside.com 2019 - 2024. All rights reserved.