【问题标题】:Opening a web page from a C# console app从 C# 控制台应用程序打开网页
【发布时间】:2018-07-09 13:35:47
【问题描述】:

我是 C# 编程新手,请见谅。我刚刚尝试了上一个问题中提出的解决方案,但没有奏效。顺便说一句,我仍然需要帮助。 我正在尝试用 C# 编写一个简单的控制台应用程序,它可以打开一个网页,也就是 http://www.libero.it。 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

class OpenWeb {

     static void Main(string[] args) {
        var prs = new ProcessStartInfo("chrome.exe");
        prs.Arguments = "http://www.libero.it";
      //  Process.Start(prs);
       try
    {
        Process.Start(prs);
    }
    catch (System.ComponentModel.Win32Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
     }
}

我不明白为什么我的代码不起作用,总是有一个异常,没有try-catch如下:

Unhandled Exception: System.ComponentModel.Win32Exception: The specified file         
could not be found
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo     
startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at OpenWeb.Main(String[] args) in C:\Users\p3rtp\myProve\Prove.cs:line 12

我使用 Windows 7x64,带有 .Net core sdk 2.1.301 e MS Visual Studio Code 1.24.1。

【问题讨论】:

  • chrome.exe 不在 PATH 中 - 甚至可能没有安装。
  • 您的路径中是否有 chrome.exe,即您是否希望该程序仅从 chrome.exe 中找到它?您可以将 URL 传递给 shell,以便它使用其配置的浏览器,并且它会知道路径。
  • 您需要定义Chrome.exe的绝对路径例如“C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe”
  • chrome.exe 不太可能与您的 .NET 应用程序位于同一文件夹中。如果您不指定文件夹,.NET 将在其运行的文件夹中以及当前用户的 Windows PATH 变量中查找此文件。因此,除非 chrome.exe 也在用户的 PATH 变量中,否则这将失败。要么将其添加到 PATH 中,要么也使用完整的文件夹名称。也不能保证 Chrome 会安装在用户的机器上——也许你需要一个后备机制来让它运行 I.E.如果找不到 Chrome。

标签: c#


【解决方案1】:

我一直在使用这一行来启动默认浏览器:

System.Diagnostics.Process.Start("http://www.google.com");

【讨论】:

    【解决方案2】:

    代码很简单,如下:

    using System
    using System.Collections.Generic
    using System.Text
    using System.Diagnostics
    namespace example
    {
       class examp
       {
          static void Main(string[] args)
          {
             Process.Start("http://www.google.com");
          }
       }
    }
    

    【讨论】:

    • 我相信您缺少某些 dll。
    【解决方案3】:

    好的,我找到了正确答案:

    var prs = new ProcessStartInfo(@"C:\Program Files 
       (x86)\Google\Chrome\Application\chrome.exe");
    

    问题不在于路径,而是在应用程序或文件夹中:只是在 chrome 的完整路径之前带有"@" 的引号我终于设法解决了问题。 总之谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多