I have a app that when you click a button it opens a file that is on a SharePoint share. In IE it will open the document in word correctly that if you make changes to the file it will push the changes back to the SharePoint server, however if a user has Firefox as their default browser Firefox will download the file first then use the local copy. Is there a way to force the program to open the link in IE instead of the default browser (or to Word directly, however I need to pass the users domain credentials before I get access to the file)?
BackgroundWorker bw = new BackgroundWorker();
GeneratingChecklist frmProgressBar = new GeneratingChecklist();
frmProgressBar.Show();
bw.DoWork += (sender, e) =>
{
e.Result = Build(AccountNumber, PracticeName, ContractID, EducationDate, MainContactInfo, Address);
};
bw.RunWorkerCompleted += (sender, e) =>
{
frmProgressBar.Close();
running = false;
if (e.Result != null)
{
System.Diagnostics.Process.Start(((FileDetails)e.Result).Address);
}
else
{
MessageBox.Show("An error occurred generating or retrieving the educator checklist.");
}
};
bw.RunWorkerAsync();
FileDetails.Address contrains the url to the word document.
Try:
System.Diagnostics.Process.Start("iexplore.exe", "http://sp.path.to/your/file.doc")
See the MSDN documentation for more information about opening processes with arguments.
Related
I've created an VSTO-Add-In for Outlook, which imports several data from an pdf-file and saves the data as an MS-Excel-File. After successfully process i start a Toastnotification ,which enables an fast opening of this Excel-file by clicking on the notification in the info-center. The problem: clicking on the notification of other incoming e-mails (Outlook) doesn't work anymore. Nothing happens. How can i solve this problem?
public Ribbon1()
{
Initialize();
}
private async Task Initialize()
{
await Task.Run(() =>
{
ToastNotificationManagerCompat.OnActivated += async toastArgs =>
{
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
await Task.Run(() =>
{
if (!string.IsNullOrEmpty(toastArgs.Argument) && !toastArgs.Argument.Contains("idEPST=ignore") && toastArgs.Argument.Contains("idEPST="))
{
string datei = toastArgs.Argument.ToLower().Replace("idEPST=", String.Empty).Trim().Replace(".xls", "");
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = "excel.exe";
si.Arguments = $"\"C:\\folder\\file.xls\" /{datei}";
Process.Start(si);
}
});
};
});
}
}
//and later
new ToastContentBuilder()
.AddAudio(null, silent: true)
.AddArgument("idEPST", filename)
.AddHeader("identifier", "My Excel App Name", String.Empty)
.AddText($"{name}, {firstname}", hintMaxLines: 1)
.AddText("... sucessfully saved.")
.Show();
After deinstalling the VSTO-Add-In: On clicking on a e-mail-notification results in an error message:
"Cannot Start Microsoft Outlook. The Command Line Argument Is Not Valid..."
It seems there are some problems with windows registry keys, especially with .msg file associations. Because when you click on a toast notification in Outlook a corresponding item is displayed/opened.
Re-associate the .msg file by following the steps and verify the results.
Click on Start and then Default Programs.
Click on Associate a file type protocol with a program option.
Select .msg from the Name list and then click on Change Program.
Now click to select Microsoft Office Outlook and then click on OK.
Restart the computer and then try opening emails saved on the Computer.
See Error: The command line argument is not valid. Verify the switch you are using. for more information.
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
}
}
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" ?!
I try to open temporary HTML file with default browser and delete the file then:
var tempFileName = Path.ChangeExtension(Path.GetTempFileName(), "html");
// I save document to temp file here...
Process process = null;
try
{
process = Process.Start(tempFileName);
}
catch (Win32Exception)
{
}
catch (ObjectDisposedException)
{
}
catch (FileNotFoundException)
{
}
var worker = new BackgroundWorker();
worker.DoWork += (s, we) => {
if (process != null)
{
process.WaitForExit();
try
{
File.Delete(tempFileName);
}
catch (IOException)
{
}
}
};
worker.RunWorkerAsync();
Unfortunately, Process.Start returns null if a process is not started, but a running one is used (new tab is opened in Google Chrome). So I can't wait for that process to exit.
So, a general question is: how to do the task? How to show a temporary HTML file to a user and delete it after viewing?
If you use ProcessStartInfo and set UseShellExecute then you can start the user's default browser by "running" the HTML directly like you're trying to do now. I haven't tried it, but it should give you a Process back to determine when the user has closed the browser.
I would still prepare for a bunch of edge cases you have no control over. Such as if they leave the browser open but close the app that's watching the browser. At that point do you let the browser stay alive? Do you kill it? When do you delete the HTML file? It might be better to use the Web Browser control. Then you don't even have to worry about other processes or browser compatibility. You can even stream the HTML contents to the control and there is no file to delete later.
You can force a new browser instance, by first figuring out the default browser, and executing it manually:
public Process launchBrowser(string url)
{
string browserName = "iexplore.exe";
using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
{
if (userChoiceKey != null)
{
object progIdValue = userChoiceKey.GetValue("Progid");
if (progIdValue != null)
{
if(progIdValue.ToString().ToLower().Contains("chrome"))
browserName = "chrome.exe";
else if(progIdValue.ToString().ToLower().Contains("firefox"))
browserName = "firefox.exe";
else if (progIdValue.ToString().ToLower().Contains("safari"))
browserName = "safari.exe";
else if (progIdValue.ToString().ToLower().Contains("opera"))
browserName = "opera.exe";
}
}
}
return Process.Start(new ProcessStartInfo(browserName, url));
}
Then you can get a handle to the process:
var process = launchBrowser("www.google.com");
process.WaitForExit();
try
{
//Do whatever
}
catch (IOException)
{
}
You can also read the html content into a Memory Stream or into a string variable using WebClient, and after close the Stream or WebClient, file will be released, ready to be deleted, as you no longer need it.
Them you have the html content in memory, just send it to browser.
Here some example if you need:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/060ea8e0-cc63-44a3-b0dc-b531c29b8a0f/read-html-content-using-cnet?forum=csharpgeneral
Hope it helps.
I want to be able to open a PDF using the native Windows Reader Application when a user clicks on a button. So far I am able to use the following code to successfully open files that end with the (.PNG) extension. However, when I let the link to open the (.PDF) file I get the following error.
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
The file destination is correct.
Here is my code:
private async void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Path to the file in the app package to launch
string imageFile = #"Data\Healthcare-Flyer.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
}
When you add PDF document in project, you have to change it's build action.
Right click on PDF document.
Click on properties.
Change Build Action from None to Content