【问题标题】:exit console app after completing process完成过程后退出控制台应用程序
【发布时间】:2018-12-07 20:21:30
【问题描述】:

您好,我的控制台应用程序用于下载 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();

【问题讨论】:

  • 你的问题是什么?
  • 你说的是程序退出时关闭窗口吗?这可能是窗口管理器设置、“退出时关闭”或类似设置。
  • 感谢您分享您的计划!是什么阻止您实施它们?
  • File.Exists() msdn.microsoft.com/en-us/library/… 是您寻找的一个很好的起点
  • 在这里得到了类似的回答。 stackoverflow.com/questions/5682408/…

标签: c# .net console-application


【解决方案1】:

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

File.WriteAllText(txtDir, reply); 之后的内容可能是:

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

当你想退出时,让你程序在到达main的末尾时关闭或者使用Enviroment.Exit(0)

【讨论】:

    【解决方案2】:

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

    if(System.IO.File.Exists(路径名))

    {

     System.Environment.Exit(0);
    

    }

    // 在这里做点别的事情来恢复

    【讨论】:

      猜你喜欢
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2017-12-31
      • 2013-06-08
      相关资源
      最近更新 更多