Monday, June 11, 2007

Open URL in Browser using C#.NET for windows applications

Open URL in Browser using C#.NET for windows applications
===========================================

using System.Diagnostics;
using Microsoft.Win32;

//Usage: OpenUrl("http://computerbapu.blogspot.com");

//Try to open a url from C#.NET window's code
//Please using the namespace System.Diagnostics to access Process class
public void OpenUrl(string url) {
try
{
string targetURL = url;
Process p = new Process();
//get default browser
p.StartInfo.FileName = getMyDefaultBrowser();
p.StartInfo.Arguments = targetURL;
p.Start();
}
catch (Exception err)
{
MessageBox.Show("Problem : " + err.Message);
}
}



//the below code gets default browser. The entry is stored in the registry.
//To access registry key please use the namespace Microsoft.Win32

private string getMyDefaultBrowser() {
string browser = string.Empty;
RegistryKey myKey = null;
try
{
mykey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);
browser = mykey.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
}
}
finally
{
if (mykey != null) mykey.Close();
}
return browser;
}

1 comment:

Jalpesh Vadgama said...

You dont have to write that much code.
here is cod that works fine..


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

Regards,
Jalpesh
http://jalpesh.blogspot.com