【问题标题】:Google Chrome cannot open from application using Process.Start()Google Chrome 无法使用 Process.Start() 从应用程序打开
【发布时间】:2013-10-18 05:15:24
【问题描述】:

我用 c# 编写了 windows 应用程序,在标签单击事件时在默认浏览器中打开网站。我的默认浏览器是谷歌浏览器。因此,当我启动我的应用程序并单击标签时,它无法在 Chrome 中打开网站。 Chrome 抛出错误“无法创建数据目录 - Google Chrome 无法读取和写入其数据目录”。我正在使用“System.Diagnostics.Process.Start”来启动进程。

一件有趣的事情是,当我关闭我的应用程序并重新打开它时。它成功地在默认 Chrome 浏览器中打开网站。 :)

我尝试使用 Process.StartInfo 的各种选项,但从未成功。下面是运行网站的方法。

我正在使用 Windows 8-64Bit 和 .Net Framework 4。请你帮我解决这个问题。

测试1:

public static void RunWebClient()
{
    Process proc = new Process();

    Microsoft.Win32.RegistryKey subKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command");
    String DefaultBrowser = subKey.GetValue(null).ToString();

    if (DefaultBrowser != null)
    {
        int startIndex = DefaultBrowser.IndexOf("\"") + 1;
        int endIndex = DefaultBrowser.IndexOf("\"", startIndex);
        string RegDefaultBrowserPath = DefaultBrowser.Substring(startIndex, endIndex - startIndex);

        proc.StartInfo.FileName = RegDefaultBrowserPath;
        proc.StartInfo.Arguments = @"http://localhost/Test/";
        proc.StartInfo.UseShellExecute = true;
        proc.StartInfo.LoadUserProfile = false;
        proc.Start();
    }
}

测试2:

public static void RunWebClient()
{
    System.Diagnostics.Process.Start("http://localhost/Test/");
}

【问题讨论】:

  • 我不确定这是否相关,但在利用 ShellExecute 时,这行 proc.StartInfo.FileName = RegDefaultBrowserPath; 不是必需的。此外,我怀疑将LoadUserProfile 设置为false。只需使用 shell 启动 URL,其余部分不用管。
  • 你有没有开启UAC之类的东西?
  • 对于路径操作,使用System.IO.Path 类,而不是简单的字符串函数。
  • @neoistheone proc.StartInfo.FileName 必须提供,否则会抛出错误“无法启动进程,因为未提供文件名”。没错,LoadUserProfile 不是必需的,但我认为它可能会导致 chrome 数据目录问题,所以我使用了它。
  • @lan 我机器的 UAC 设置为默认

标签: c# google-chrome process web


【解决方案1】:

我会尝试将 WorkingDirectory 添加到您的 ProcessStartInfo 类中

proc.StartInfo.FileName = Path.GetFileName(RegDefaultBrowserPath);
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(RegDefaultBrowserPath);

将完整的文件名传递给 FileName 属性不足以为启动的文件设置当前工作目录。

【讨论】:

  • 感谢您的回复!!我试过了,但同样的错误。我只在 Windows 8 上遇到这个问题,而不是在 Windows 7 上。
  • 您是否尝试过移动 FileName 属性中的参数值?我的意思是,您只是想使用默认浏览器(Chrome 或其他),所以让 shell 选择它。移动 FileName 属性中的 Arguments 值应该会启动当前浏览器。
  • 是的,我已经尝试将参数移动到 FileName 属性。此外,我仅在使用我的默认浏览器 Chrome 时遇到此问题。
  • 另一件事,当我以管理员身份运行 chrome 时;它运行成功。但是我不能使用它,因为它要求普通用户的密码是不允许的。 if ((System.Environment.OSVersion.Version.Major >= 6) && (DefaultBrowserPath.IndexOf("chrome") != -1)) { proc.StartInfo.Verb = "runas"; }
  • 调试代码后,我发现应用程序是通过Win32 API CreateProcessAsUser 由一个服务启动的。所以问题的根本原因应该是在启动应用程序之前需要设置的权限问题。我正在尝试使用 CreateProcessAsUser 的 securityAttributes 参数设置权限。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多