Open link in browser from code behind of installed application C# - c#

I have made a winform application. When I run the app in visual studio, following code works to open a link from DataGridView link column.
System.Diagnostics.Process.Start("chrome.exe",
grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
But when I install the build and try to do the same thing, nothing happens. Is there any other setting that I need to make.
Please help.

If you want to open link link from your DataGridView, you should actually pass url not web browser, ie.:
System.Diagnostics.Process.Start(grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
It will end up trying to open given url with default browser for OS.
Ofc make sure that link of url from url is properly formatted.
If chrome.exe doesn't work for launching, maybe try shortened one: chrome?
Can you also confirm that Win+R (a.k.a. Run...) and then chrome.exe actually opens up Chrome?
If not, can you check if
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ contains chrome.exe entry?
If so, maybe url formatting is wrong?

You can open a URL in browser with the following snippets:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "http://google.com";
process.Start();
or
System.Diagnostics.Process.Start("http://google.com");
In your example, to allow users to launch it from the DataGridView, you should simply define a click event like this:
private void grdRelLinks_CellContentClick(object pSender, DataGridViewCellEventArgs pArgs)
{
if (pArgs.RowIndex > -1 && pArgs.ColumnIndex == 2)
{
string url = grdRelLinks.Rows[pArgs.RowIndex].Cells[pArgs.ColumnIndex].Value.ToString();
if(!string.IsNullOrWhiteSpace(url))
System.Diagnostics.Process.Start(url);
}
}

This worked for me.
private void OnGridViewContentClick(object sender, EventArgs e)
{
string chromeExePath = CheckIfChromeIsInstalled();
if (!string.IsNullOrEmpty(chromeExePath))
{
MessageBox.Show("Yayy Chrome.exe was found !");
//Path is not null:
Process.Start(chromeExePath, "http://www.google.de");//Here you can also enter the URL you get from your GridView
string url = grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString();
if(!url.StartsWith("http")
{
url = $"http://{url}";
}
Process.Start(chromeExePath, url);
}
else
{
MessageBox.Show("Chrome.exe not found");
}
}
private string CheckIfChromeIsInstalled()
{
DirectoryInfo programFiles = new DirectoryInfo(Environment.GetEnvironmentVariable("PROGRAMFILES"));//Find your Programs folder
DirectoryInfo[] dirs = programFiles.GetDirectories();
List<FileInfo> files = new List<FileInfo>();
Parallel.ForEach(dirs, (dir) =>
{
files.AddRange(dir.GetFiles("chrome.exe", SearchOption.AllDirectories)); //Search for Chrome.exe
});
//files should only contain 1 entry
//Return path of chrom.exe or null
return (files.Count > 0) ? files[0].FullName : null;
}
NOTE: Starting this in an extra Thread could be useful !
EDIT :
Can you please check if cmd.exe works with start chrome.exe "your URL" ?!

Related

How to start Zoom meeting automatically from C# Console Application

I am trying to build a simple app (As Console Application) that enters a Zoom meeting automatically at a specified time.
The app opens the Zoom meeting using Process.Start function, and then wait for the "Zoom Meeting" process to start.
It works well if I use a Windows shortcut file (.lnk extension) with the correct parameters, like shown here
But is doesn't work when I use the "regular" Zoom link (the url) because it opens the browser and waits for user input (It shows an alert).
I know how to send input to a process, so all I need is to a reference to the browser window that opened, but I can't find it.
The Process.Start doesn't return it and when I looped through all processes (Process.GetProcesses) I couldn't find any useful name that I can search for.
So, how can I get a reference to the browser process? Or at least send it input when it start.
Thanks in advance.
=== EDIT ===
After digging in Windows Registry, I have found an even simpler code to achieve it:
public static void OpenZoomMeeting(string link)
{
string zoomDirectory = Environment.ExpandEnvironmentVariables(#"%APPDATA%\Zoom\bin");
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = $#"{zoomDirectory}\Zoom.exe",
Arguments = $"--url={link}",
WorkingDirectory = zoomDirectory
};
Process.Start(startInfo);
}
=== OLD CODE ===
Found the solution thanks to jdweng
He said that I should to use a WebBrowser to open the meeting without the prompt, so I looked into it.
Because my app is a Console Application, I can't just use a WebBrowser so I found That solution and it worked for me.
Thank you for your help
===The code===
private void RunBrowserThread(string url) {
var th = new Thread(() => {
var br = new WebBrowser();
br.DocumentCompleted += Browser_DocumentCompleted;
br.Navigate(url);
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
var br = sender as WebBrowser;
if (br.Url == e.Url) {
Console.WriteLine("Natigated to {0}", e.Url);
Application.ExitThread(); // Stops the thread
}
}

How can I remove google chrome cookies

I'm trying to remove cookies of chrome browser. Firstly I declared the path
string chromeLocation1 = "C:\\Users\\" + Environment.UserName.ToString() + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Local Storage";
When I try to run my remove code "The file is in use by another program or user" error appears. So I tried to kill chrome.exe's proccess
foreach (var process in Process.GetProcessesByName("chrome.exe"))
{
process.Kill();
}
But now it gives me "Access Denied" error even I run it as administrator. What should I do to remove these cookies?
You can delete all cookies with selenium framework.
1) Install selenium framework - Selenium WebDriver and Selenium WebDriver Support Classes (the easiest way to do this is by using NuGet)
2) Use the following code to delete all cookies:
var chromeUserData = "C:\\Users\\" + Environment.UserName.ToString(CultureInfo.InvariantCulture) + "\\AppData\\Local\\Google\\Chrome\\User Data";
var chromeAdvancedSettings = "chrome://settings/clearBrowserData";
var options = new ChromeOptions();
options.AddArgument("--lang=en");
options.AddArgument("--user-data-dir=" + chromeUserData);
options.LeaveBrowserRunning = false;
var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl(chromeAdvancedSettings);
var frame = driver.FindElement(By.XPath("//iframe[#src='chrome://settings-frame/clearBrowserData']"));
var frameDriver = driver.SwitchTo().Frame(frame);
var dropDown = new SelectElement(frameDriver.FindElement(By.Id("clear-browser-data-time-period")));
dropDown.SelectByIndex(4);
var elm = driver.FindElement(By.Id("delete-cookies-checkbox"));
if (!elm.Selected) elm.Click();
elm = driver.FindElement(By.XPath("//button[#id='clear-browser-data-commit']"));
elm.Click();
var waiter = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
waiter.Until(wd => wd.Url.StartsWith("chrome://settings"));
driver.Navigate().GoToUrl("chrome://newtab");
[Selenium documentation]
if You want to delete your browser all data using C# language then you can delete each browser history,cookies etc (all data) using different code.
Here i write some code for deleting all data of Internet explorer
1-- Delete all data/History of Internet Explorer in a button click (Window Form application or WPF application)
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
}
2--- Now the importent browser Google Chrome (the mystery because everyone try to delete all history of it using SQLite but it wrong). Dont use SQLite database because google chrome Hold all data( History, Cookies, and etc) in following location
C:\Users\UserName(Your PC Name)\AppData\Local\Google\Chrome\User Data
just delete all 'User Data' Folder or all the folders and files within it. then you will see your all history and cookies clear.
Following is the code for it.
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
// for Google Chrome.
string rootDrive = Path.GetPathRoot(Environment.SystemDirectory); // for getting primary drive
string userName = Environment.UserName; // for getting user name
// first close all the extension of chrome (close all the chrome browser which are opened)
try
{
Process[] Path1 = Process.GetProcessesByName("chrome");
foreach (Process p in Path1)
{
try
{
p.Kill();
}
catch { }
p.WaitForExit();
p.Dispose();
}
System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(rootDrive + "Users\\"+userName+"\\AppData\\Local\\Google\\Chrome\\User Data");
try
{
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
file.Delete();
}
}
catch { }
try
{
foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
{
dir.Delete(true);
}
}
catch { }
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
label1.Text = " History Deleted successfully.";
}
you can clear the cookies history and cache by following the below console application
https://stackoverflow.com/a/57111667/9377382

open window explorer folder from my results c#

iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.

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();

Simple silverlight open-file-dialog errors

A while back I wrote a silverlight user control which had a csv import/export feature. This has been working fine, until recently I discovered it erroring in one scenario. This may have been due to moving to Silverlight 3.
The Error:
Message: Unhandled Error in Silverlight 2 Application
Code: 4004
Category: ManagedRuntimeError
Message: System.Security.SecurityException: Dialogs must be user-initiated.
at System.Windows.Controls.OpenFileDialog.ShowDialog()
at MyControl.OpenImportFileDialog()
at ...
The Code:
private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(lblFileName.Text))
{
if (MessageBox.Show("Are you sure you want to change the Import file?", "Import", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
{
return;
}
}
EnableDisableImportButtons(false);
var fileName = OpenImportFileDialog();
lblFileName.Text = fileName ?? string.Empty;
EnableDisableImportButtons(true);
}
private string OpenImportFileDialog()
{
var dlg = new OpenFileDialog { Filter = "CSV Files (*.csv)|*.csv" };
if (dlg.ShowDialog() ?? false)
{
using (var reader = dlg.File.OpenText())
{
string fileName;
//process the file here and store fileName in variable
return fileName;
}
}
}
I can open an import file, but if i want to change the import file, and re-open the file dialog, it errors. Does anyone know why this is the case?
Also, I am having trouble debugging because placing a breakpoint on the same line (or prior) to the dlg.ShowDialog() call seems to cause this error to appear as well.
Any help would be appreciated?
You do two actions on one user click.
You show a messagebox which effectively uses your permission to show a dialog on user action.
You then try to show the dialog, since this is a second dialog on user action it's not allowed.
Get rid of the confirmation dialog and you'll be fine.
Remove Break Points before if (dlg.ShowDialog() ?? false) code will run its work for me.

Categories