前段时间做项目的时候遇到了一个问题,用System.Diagnostics.Process.Start(url)方法打开连接总是报错,System.ComponentModel.Win32Exception: 系统找不到指定的文件。调试也没弄出个所以然了,还好公司以前也有人遇到过这个问题,就给了我下面这个方法,我如获至宝,果然解决了问题。
/// <summary>
/// 根据默认浏览器打开网页
/// </summary>
/// <param name="url">要打开的链接</param>
/// <param name="openInNewWindow">是否在新窗口打开</param>
/// <returns></returns>
public static bool OpenUrl(string url, bool openInNewWindow)
{
try
{
const string name = @"http\shell\open\command";
RegistryKey openSubKey = Registry.ClassesRoot.OpenSubKey(name, false);
if (openSubKey != null)
{
string fileName = ((string)openSubKey.GetValue(null, null)).Split(new[] { '"' })[1];
if (openInNewWindow)
{
Process process = new Process();
process.StartInfo.FileName = fileName;
process.StartInfo.Arguments = url;
process.Start();
return true;
}
Process.Start(fileName, url);
}
}
catch (Exception)
{
try
{
Process.Start(url);
return true;
}
catch (Exception)
{
return false;
}
}
return true;
}