Selenium Webdriver, C# output to console after opening driver - c#

Hi I am using Selenium for the first time and I was doing the following code. It runs fine but after opening firefox it wont output to console as the code says it should it will do all of it after all the steps in the code are complete.
So my question is how do I make that text output to console while its actually running the step?
var ProxyIP = "xxx.xxx.xx.xxx:80";
RtbConsole.AppendText("Setting Up Firefox\n");
//Firefox driver + proxy setup
FirefoxProfile profile = new FirefoxProfile();
String PROXY = ProxyIP;
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy = PROXY;
proxy.FtpProxy = PROXY;
proxy.SslProxy = PROXY;
profile.SetProxyPreferences(proxy);
RtbConsole.AppendText("Launching Firefox\n");
FirefoxDriver driver = new FirefoxDriver(profile);
RtbConsole.AppendText("Navigating to http://whatsmyip.net/ \n");
driver.Navigate().GoToUrl("http://whatsmyip.net/");
IWebElement ip = driver.FindElement(By.XPath("/html/body/div/div/h1/span"));
var myIP = ip.Text;
RtbConsole.AppendText("Checking IP for Proxy\n");
if (ProxyIP == myIP + ":80") {
RtbConsole.AppendText("Proxy Test: Success\n");
} else {
RtbConsole.AppendText("Proxy Test: Failed\n");
}
//Close the browser
driver.Quit();

I'm new to this site, so i apologize if this is not helpful. However, when i am writing selenium(webdriver) tests in C#, i generally do not use the append command. Try approaching the console differently, such as
Console.WriteLine("Text you wish to be outputted to the Console");
//OR MAYBE
Console.Write("Text you wish to be outputted to the Console");
In addition, i am not sure that simultaneously executing two commands is actually possible, however, you can make the output contingent upon other chosen code executing, using if statements, or maybe try catch etc.
Hope that this helps! Cheers!

Related

C# Selenium - Failed to Start Tor

I'm trying to launch Tor browser through Selenium in C# using the following code:
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AutomatorApp
{
public class BrowserAutomator
{
public void Automate()
{
String torPath = "D:\\Tor Browser\\Browser\\firefox.exe";
String profilePath = "D:\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default\\";
FirefoxProfile profile = new FirefoxProfile(profilePath);
profile.SetPreference("network.proxy.type", 1);
profile.SetPreference("network.proxy.socks", "127.0.0.1");
profile.SetPreference("network.proxy.socks_port", 9153);
profile.SetPreference("network.proxy.socks_remote_dns", false);
FirefoxDriverService firefoxDriverService = FirefoxDriverService.CreateDefaultService("D:\\geckodriver-v0.26.0-win64", "geckodriver.exe");
firefoxDriverService.FirefoxBinaryPath = torPath;
var firefoxOptions = new FirefoxOptions
{
Profile = profile,
LogLevel = FirefoxDriverLogLevel.Trace
};
FirefoxDriver driver = new FirefoxDriver(firefoxDriverService, firefoxOptions);
}
}
}
However, this shows the error 'Tor Failed to Start' and the exception simply contains 'Permission denied'. I tried launching the app in administrator mode and ensuring that the folder is accessible by all users but this did not solve the issue.
Interestingly, when I try to launch a Firefox browser using the same setup it works well.
Any help is very much appreciated.
Update - Solved: After updating to the latest Tor version (9.5.1) The final working code:
FirefoxProfile profile = new FirefoxProfile(profilePath);
profile.SetPreference("network.proxy.type", 1);
profile.SetPreference("network.proxy.socks", "127.0.0.1");
profile.SetPreference("network.proxy.socks_port", 9153);
profile.SetPreference("network.proxy.socks_remote_dns", false);
FirefoxDriverService firefoxDriverService = FirefoxDriverService.CreateDefaultService(geckoDriverDirectory);
firefoxDriverService.FirefoxBinaryPath = torPath;
firefoxDriverService.BrowserCommunicationPort = 2828;
var firefoxOptions = new FirefoxOptions
{
Profile = null,
LogLevel = FirefoxDriverLogLevel.Trace
};
firefoxOptions.AddArguments("-profile", profilePath);
FirefoxDriver driver = new FirefoxDriver(firefoxDriverService, firefoxOptions);
driver.Navigate().GoToUrl("https://www.google.com");
Important notes:
The following TOR configs need to be changed in about:config :
marionette.enabled: true
marionette.port: set to an unused port, and set this value to firefoxDriverService.BrowserCommunicationPort in your code. This was set to 2828 in my example.
As far as I remember from my attempts a few years ago, TOR with WebDriver didn't work when you set that "Profile" option. Normal Firefox works, but TOR simply doesn't.
If you get a timeout error after this, make sure marionette is enabled on about:config. If it's already enabled, follow what is going on with TOR on start up. Like if the actual firefox browser doesn't load up, stuck at connection launhcer etc, or there is a message box at the browser startup or something... And also make sure no other firefox.exe, geckodriver.exe or tor.exe is running on the background. If multiple executubles are not configured to listen different port numbers, it might cause problems.
Environment.SetEnvironmentVariable("webdriver.gecko.driver", "C:\\TorBrowser\\Browser\\geckodriver.exe");
var gekcoService = FirefoxDriverService.CreateDefaultService("C:\\TorBrowser\\Browser", "geckodriver.exe");
var gekcoService.FirefoxBinaryPath = "C:\\TorBrowser\\Browser\\firefox.exe";
// marionette port that browser listens to. I had it set to a custom port on about:config
var gekcoService.BrowserCommunicationPort = 50111;
// also had given a custom port for geckodriver listen port
var gekcoService.Port = 9881;
var gekcoService.Host = 127.0.0.1;
var gekcoService.HostName = 127.0.0.1;
var gekcoService.Start();
var ffOptions = new FirefoxOptions
{
AcceptInsecureCertificates = true,
BrowserExecutableLocation = "C:\\TorBrowser\\Browser\\firefox.exe",
Profile = null,
UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss
};
ffOptions.AddArguments("-profile", "C:\\TorBrowser\\Browser\\TorBrowser\\Data\\Browser\\profile.default");
ffOptions.LogLevel = FirefoxDriverLogLevel.Info;
ffOptions.PageLoadStrategy = PageLoadStrategy.Eager;
var ffDriver = new FirefoxDriver(gekcoService, ffOptions);
ffDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10);
ffDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10);
ffDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
Your code block looks perfect to me.
However there seems to be an issue opening the tor Browser 9.5 which uses the default Firefox v68.9.0esr.
You can find a detailed discussion in How to initiate a Tor Browser 9.5 which uses the default Firefox to 68.9.0esr using GeckoDriver and Selenium through Python
Solution
The solution will be to install and use either of the following browsers:
Firefox v77.0.1
Firefox Nightly v79.0a1
In case you use the above mentioned browsers, you need to:
Firefox v77.0.1:
String torPath = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
Firefox Nightly v79.0a1
String torPath = "C:\\Program Files\\Firefox Nightly\\firefox.exe";

Selenium disable Restore pages poup

i am using selenium C#, i am trying to disable the pop up of "crashed" chrome:
i tried to set the profile preferences, but its seems that the it ain't changing at all, the code:
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("exit_type", "Normal");
options.AddUserProfilePreference("exited_cleanly", "true");
IWebDriver driver = new ChromeDriver(options);
i tried to change the value of exit type to none & None, but without any change at the preferences document.
I'm using C# and I've noticed that chrome driver can be closed propery only when we use Close() method followed by Quit() in finally block. No special options required. I think in java it's the same way. This will help to rid of "Restore pages" while launching chrome with the driver
ChromeOptions options = new ChromeOptions();
options.AddArgument(Configure.chromeProfileDir);
options.AddArgument(Configure.chromePath);
ChromeDriver d = null;
try
{
d = new ChromeDriver(options);
d.Navigate().GoToUrl("https://google.com");
// Your operations...
}
catch(Exception e)
{
// Handle your exceptions...
}
finally
{
try
{
d.Close();
d.Quit();
}
catch(Exception e)
{
}
}
I tested the Answer given by #Icy, and it worked for me. what I used was :
prefs = {'exit_type': 'Normal'}
option.add_experimental_option("prefs", {'profile': prefs})
and it is spoken of by https://superuser.com/a/1343331, only issue is with the method listed there, you will need to edit the file manually every time, so this works way better, tested in may 2021. Just couldn't upvote the answer as I have no reputation yet, and it is the last.
Use below code to handle this pop up:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArguments("--disable-application-cache");
driver = new ChromeDriver(options);
i tried this code in java, it solved my problem :))
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir="+profilepath);
options.addArguments("--no-startup-window");
// argument "--no-startup-window" make chrome is failed to start -> selenium will quit chrome normaly
//-> start chrome again, it won't show restore page
try {
driver = new ChromeDriver(options);
}catch(Exception ex){
}
options = new ChromeOptions();
options.addArguments("user-data-dir="+profilepath);
driver = new ChromeDriver(options);
Try this code:
prefs = {'exit_type': 'Normal'}
chrome_options.add_experimental_option("prefs", {'profile': prefs})

How to authenticate (user/password) proxy in c# selenium chrome driver

I have a HTTP/HTTPS proxy which need to authenticate using username and password. How do I do that using C# selenium chrome webdriver?
string host = proxies[count].Split(':')[0];
int port = Convert.ToInt32(proxies[count].Split(':')[1]) + 1;
string prox = host + ":" + port.ToString();
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy = prox;
proxy.SslProxy = prox;
options.Proxy = proxy;
options is the ChromeOptions class which I assign to the driver.
I created little package for yor problem (https://github.com/RDavydenko/OpenQA.Selenium.Chrome.ChromeDriverExtensions)
Install Package:
Install-Package OpenQA.Selenium.Chrome.ChromeDriverExtensions -Version 1.2.0
Use for your ChromeOptions:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
...
var options = new ChromeOptions();
// Add your HTTP-Proxy
options.AddHttpProxy(PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD);
var driver = new ChromeDriver(options); // or new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory, options);
driver.Navigate().GoToUrl("https://whatismyipaddress.com/"); // Check your IP
Instead of PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD, use the parameters of your proxy
The only successful approach I have found is to use AutoIT ( https://www.autoitscript.com/site/autoit ).
I have mine setup for proxy authentication for all of the major browsers, but this should work for Chrome.
I wrote this on my phone from memory. If it doesn't work let me know and I'll correct.
WinWait("data:, - Google Chrome","","10")
If WinExists("data:, - Google Chrome","")Then
WinActivate("data:, - Google Chrome")
Send("USERNAMEGOESHERE"{TAB}")
Send("USERPASSWORDGOESHERE"{ENTER}")
Using AutoIT, create this as a script, compile it to exe, save it somewhere and reference the file with the following (Java code):
Runtime.getRuntime().exec("C:\\users\\USERID\\desktop\\FILENAME.exe");
I find it best to call the proxy script a step BEFORE you call the URL that triggers the proxy auth.
2019 Update
After multiple unfortunate attempts, the easiest solution is to create an extension for Chrome as explained by Mike in this post.
It sounds freaky, but it is actually really straightforward.
2021 Update
I have created a simple library (nuget package) that helps you with selenium proxy authentication. You can check the source at Github repo. It also works when using driver headless.
Usage:
public void Test()
{
// Create a local proxy server
var proxyServer = new SeleniumProxyAuth();
// Don't await, have multiple drivers at once using the local proxy server
TestSeleniumProxyServer(proxyServer, new ProxyAuth("123.123.123.123", 80, "prox-username1", "proxy-password1"));
TestSeleniumProxyServer(proxyServer, new ProxyAuth("11.22.33.44", 80, "prox-username2", "proxy-password2"));
TestSeleniumProxyServer(proxyServer, new ProxyAuth("111.222.222.111", 80, "prox-username3", "proxy-password3"));
while (true) { }
}
private async Task TestSeleniumProxyServer(SeleniumProxyAuth proxyServer, ProxyAuth auth)
{
// Add a new local proxy server endpoint
var localPort = proxyServer.AddEndpoint(auth);
ChromeOptions options = new ChromeOptions();
//options1.AddArguments("headless");
// Configure the driver's proxy server to the local endpoint port
options.AddArgument($"--proxy-server=127.0.0.1:{localPort}");
// Optional
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
// Create the driver
var driver = new ChromeDriver(service, options);
// Test if the driver is working correctly
driver.Navigate().GoToUrl("https://www.myip.com/");
await Task.Delay(5000);
driver.Navigate().GoToUrl("https://amibehindaproxy.com/");
await Task.Delay(5000);
// Dispose the driver
driver.Dispose();
}
This is for firefox but the top answer might help.
C# Selenium WebDriver FireFox Profile - using proxy with Authentication
What you can do is to create a profile and save the authentication data in it. If your profile is called "webdriver" you can select it from your code in the initialization:
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar",23);
WebDriver driver = new FirefoxDriver(profile);
Chrome won't let you use any extension for selenium web testing these days. And selenium doesn't have any built in username & password input for proxies.
The only solution I found is using AutoIt. It will automates windows level actions. While selenium only automates browser level actions.
Passing username and password to the proxy dialog box is A WINDOWS LEVEL ACTION.
To download and install AutoIt, you can go to : https://www.guru99.com/use-autoit-selenium.html
I wrote a simple AutoIt script as below :
; option to read substring in a window title
Opt("WinTitleMatchMode", 2)
; wait for proxy username & password dialog box
WinWait("- Google Chrome","","10")
; if the box shows up, write the username and password
; username & password are passed as program parameters
If WinExists("- Google Chrome","") Then
WinActivate("- Google Chrome")
; $CmdLine is a special array that holds parameters
if $CmdLine[0] = 2 Then
Send($CmdLine[1] & "{TAB}")
Send($CmdLine[2] & "{ENTER}")
EndIf
; any request dialog to save credential?
WinWait("Save password for ","","10")
; if any, close it
If WinExists("Save password for ","") Then
WinActivate("Save password for ")
Send("{TAB}")
Send("{SPACE}")
EndIf
EndIf
Exit
Compile the script to be an executable program as ProxyAuth.exe.
The program will receive two parameters : username and password.
With parameters, you can use dynamic username & password in your C# script.
Then you need to use the program in C# code as below :
ChromeOptions ChromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");
Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);
string cmd = string.Format($"{ProxyUsername} {ProxyPassword}");
Process proc = new Process();
proc.StartInfo.FileName = "ProxyAuth.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
You will need to use OpenQA.Selenium, OpenQA.Selenium.Chrome, and System.Diagnostics namespaces.
** EDIT **
If you interested in using AutoIt, you can also use their library in NuGet. Just search in "Manage NuGet Packages" : AutoIt. Choose the one and only one AutoIt package shown and install it.
With this library, you don't need to create ProxyAuth.exe application as described above.
You can use the AutoIt library and make modifications in the C# code :
ChromeOptions ChromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");
Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);
// use the AutoIt library
AutoItX.AutoItSetOption("WinTitleMatchMode", 2);
AutoItX.WinWaitActive("- Google Chrome", "", 10);
AutoItX.WinActivate("- Google Chrome");
AutoItX.Send(ProxyUsername);
AutoItX.Send("{TAB}");
AutoItX.Send(ProxyPassword);
AutoItX.Send("{ENTER}");
// dismiss save password prompt
AutoItX.WinWaitActive("Save password for ", "", 10);
AutoItX.WinActivate("Save password for ");
AutoItX.Send("{TAB}");
AutoItX.Send("{SPACE}");
Answered in another thread C# Selenium Proxy Authentication with Chrome Driver.
Main idea - use Selenium 4.0 and BiDi APIs.

Unable to open chrome with Webdriver in C#

Have gone through previous post, but the error I am facing is different.
Trying to open chrome through webdriver using C#.
namespace HelloWorld
{
public class OurFirstTest
{
static void main(String[] args)
{
IWebDriver driver = new ChromeDriver(#"D:\Automation\chromedriver");
driver.Navigate().GoToUrl("http://www.google.com");
}
}
}
During build, command prompt opens with message
Starting ChromeDriver <v2.9.248315> on port 9515.
Browser is not opening....
I Edited my code and you can follow it now, I am using this code to run chrome instance in incognito mode.
IWebDriver driver1;
ChromeOptions m_Options = new ChromeOptions();
m_Options.AddArgument("--user-data-dir=C:/Users/dell/AppData/Local/Google/Chrome/User Data/Profile 2");
m_Options.AddArgument("--disable-extensions");
m_Options.AddArgument("--silent");
m_Options.AddArgument("--incognito");
//Adding a Proxy
Proxy proxy = new Proxy();
proxy.HttpProxy = "XXXX.XXX.X.X:XXXX";
m_Options.Proxy = proxy;
driver1 = new ChromeDriver(#"F:\\ChromeDriver\", m_Options);
driver1.Navigate().GoToUrl("https://www.google.com");
Make sure you set up the right path for driver.
You'd better put your chromediver in the same directory with your test's exe file.
And update your chromedriver to the latest version which is 2.10

How to open in default browser in C#

I am designing a small C# application and there is a web browser in it. I currently have all of my defaults on my computer say google chrome is my default browser, yet when I click a link in my application to open in a new window, it opens internet explorer. Is there any way to make these links open in the default browser instead? Or is there something wrong on my computer?
My problem is that I have a webbrowser in the application, so say you go to google and type in "stack overflow" and right click the first link and click "Open in new window" it opens in IE instead of Chrome. Is this something I have coded improperly, or is there a setting not correct on my computer
===EDIT===
This is really annoying. I am already aware that the browser is IE, but I had it working fine before. When I clicked a link it opened in chrome. I was using sharp develop to make the application at that time because I could not get c# express to start up. I did a fresh windows install and since I wasn't too far along in my application, I decided to start over, and now I am having this problem. That is why I am not sure if it is my computer or not. Why would IE start up the whole browser when a link is clicked rather than simply opening the new link in the default browser?
You can just write
System.Diagnostics.Process.Start("http://google.com");
EDIT: The WebBrowser control is an embedded copy of IE.
Therefore, any links inside of it will open in IE.
To change this behavior, you can handle the Navigating event.
For those finding this question in dotnet core. I found a solution here
Code:
private void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start(url);
}
that should solve your problem
Did you try Processas mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?
You could use
Process myProcess = new Process();
try
{
// true is the default, but it is important not to set it to false
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
My default browser is Google Chrome and the accepted answer is giving the following error:
The system cannot find the file specified.
I solved the problem and managed to open an URL with the default browser by using this code:
System.Diagnostics.Process.Start("explorer.exe", "http://google.com");
I'm using this in .NET 5, on Windows, with Windows Forms. It works even with other default browsers (such as Firefox):
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
Based on this and this.
Try this , old school way ;)
public static void openit(string x)
{
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
using : openit("www.google.com");
Am I the only one too scared to call System.Diagnostics.Process.Start() on a string I just read off the internet?
public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
{
Request = request;
string url = Request.Url;
if (Request.TransitionType != TransitionType.LinkClicked)
{ // We are only changing the behavoir when someone clicks on a link.
// Let the embedded browser handle this request itself.
return false;
}
else
{ // The user clicked on a link. Something like a filter icon, which links to the help for that filter.
// We open a new window for that request. This window cannot change. It is running a JavaScript
// application that is talking with the C# main program.
Uri uri = new Uri(url);
try
{
switch (uri.Scheme)
{
case "http":
case "https":
{ // Stack overflow says that this next line is *the* way to open a URL in the
// default browser. I don't trust it. Seems like a potential security
// flaw to read a string from the network then run it from the shell. This
// way I'm at least verifying that it is an http request and will start a
// browser. The Uri object will also verify and sanitize the URL.
System.Diagnostics.Process.Start(uri.ToString());
break;
}
case "showdevtools":
{
WebBrowser.ShowDevTools();
break;
}
}
}
catch { }
// Tell the browser to cancel the navigation.
return true;
}
}
This code was designed to work with CefSharp, but should be easy to adapt.
Take a look at the GeckoFX control.
GeckoFX is an open-source component
which makes it easy to embed Mozilla
Gecko (Firefox) into any .NET Windows
Forms application. Written in clean,
fully commented C#, GeckoFX is the
perfect replacement for the default
Internet Explorer-based WebBrowser
control.
dotnet core throws an error if we use Process.Start(URL). The following code will work in dotnet core. You can add any browser instead of Chrome.
var processes = Process.GetProcessesByName("Chrome");
var path = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path, url);
This opened the default for me:
System.Diagnostics.Process.Start(e.LinkText.ToString());
I tried
System.Diagnostics.Process.Start("https://google.com");
which works for most of the cases but I run into an issue having a url which points to a file:
The system cannot find the file specified.
So, I tried this solution, which is working with a little modification:
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");
Without wrapping the url with "", the explorer opens your document folder.
In UWP:
await Launcher.LaunchUriAsync(new Uri("http://google.com"));
Open dynamically
string addres= "Print/" + Id + ".htm";
System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));
update the registry with current version of explorer
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
This works nicely for .NET 5 (Windows):
ProcessStartInfo psi = new ProcessStartInfo {
FileName = "cmd.exe",
Arguments = $ "/C start https://stackoverflow.com/",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
};
Process.Start(psi);
to fix problem with Net 6
i used this code from ChromeLauncher
,default browser will be like it
internal static class ChromeLauncher
{
private const string ChromeAppKey = #"\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe";
private static string ChromeAppFileName
{
get
{
return (string) (Registry.GetValue("HKEY_LOCAL_MACHINE" + ChromeAppKey, "", null) ??
Registry.GetValue("HKEY_CURRENT_USER" + ChromeAppKey, "", null));
}
}
public static void OpenLink(string url)
{
string chromeAppFileName = ChromeAppFileName;
if (string.IsNullOrEmpty(chromeAppFileName))
{
throw new Exception("Could not find chrome.exe!");
}
Process.Start(chromeAppFileName, url);
}
}
I'd comment on one of the above answers, but I don't yet have the rep.
System.Diagnostics.Process.Start("explorer", "stackoverflow.com");
nearly works, unless the url has a query-string, in which case this code just opens a file explorer window. The key does seem to be the UseShellExecute flag, as given in Alex Vang's answer above (modulo other comments about launching random strings in web browsers).
You can open a link in default browser using cmd command start <link>, this method works for every language that has a function to execute a system command on cmd.exe.
This is the method I use for .NET 6 to execute a system command with redirecting the output & input, also pretty sure it will work on .NET 5 with some modifications.
using System.Diagnostics.Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("start https://google.com");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();

Categories