前段時間做項目的時候遇到了一個問題,用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;
}