Access is denied exception when using Process.Start() to open folder - c#

I have a winforms application in C# where I have to open a certain Folder.
I use
System.Diagnostics.Process.Start(pathToFolder);
This results in the following exception:
System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo
startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at MyApp.openLogFolderToolStripMenuItem_Click(Object sender, EventArgs e)
I have already checked the following things:
The folder exists
The user has rights to the folder (can open it in Explorer)
Another thing is that if I use Process.Start() to open a file inside this folder, it works.
Can anyone give me a hint?Cheers
Edit
My goal is to open the folder in Explorer.
The pathToFolder is something like H:\Something\App.Name\Log

According to Microsoft Doc's the System.Diagnostics.Process.Start(string) runs the file or process (and therefore does not open the folder). For opening a folder, this doc page sugests that you might do this with System.Diagnostics.Process.Start(string, string) where first should be a way to explorer, Total commander or something similar, and second should be a argument telling the used explorer what to do (open the folder pathToFolder).
I suppose that some system variable stores the value for "default folder viewer" but I do not know where. I will try to go for it and return later with the answer.
Hope that it helps.
EDIT: I did some quick digging around and to open the folder the following should do the trick:
System.Diagnostics.Process.Start(Environment.GetEnvironmentVariable("WINDIR") +
#"\explorer.exe", pathToFolder);
Where first argument is a path to classical windows explorer and second is the actual path to the folder itself.
It seem that widows does not by itself hold path to other "folder viewer" (such as Total Commander etc.), so this way is probably off the table.

Try this:
var psi = new System.Diagnostics.ProcessStartInfo() { FileName = pathToFolder, UseShellExecute = true };
System.Diagnostics.Process.Start(psi);

I usually use this to open file/directory:
public static void OpenFile(string path, bool isDirectory = false)
{
if (string.IsNullOrEmpty(path)) return;
if ((isDirectory && Directory.Exists(path)) || (!isDirectory && File.Exists(path)))
{
ProcessStartInfo pi = new ProcessStartInfo(path);
pi.Arguments = Path.GetFileName(path);
pi.UseShellExecute = true;
pi.WindowStyle = ProcessWindowStyle.Normal;
pi.Verb = "OPEN";
Process proc = new Process();
proc.StartInfo = pi;
proc.Start();
}
}
or
Process.Start("explorer.exe",path);
If this doesn't work it may be a permission issue after all.

You can set the working directory like this but you can't run the directory itself only files or exe
var startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = //working directory
Process proc = Process.Start(startInfo);

This error actually happens when there is a difference between the default behaviour of opening the file and the relative behaviour of opening the file.
For example, if you have selected the default application to open .pdf files as Internet Explorer, and you are trying to open the same file using Process.Start() method. You will receive an exception because as per the default operations it should open that file in Internet Explorer and your application is trying to open it using Adobe reader.
To rectify this set the default application for the .pdf file as Adobe Reader and you won't receive this error any more.
You can do this by, right-clicking on the file and then select, Default program or App. Further, select the default Program or App from the list of available programs and then select the Always use the selected program/App to open files of this type.

Related

How to call the "Open With" dialog used to associate file formats in Windows 10 or 11?

MSDN says that starting in Windows 10, it is not possible to call SHOpenWithDialog to set the file association for the specified format.
When I tried to invoke the following two commands, neither of the "Open With" dialog boxes were able to set the file association.%1 is a full file path.
OpenWith.exe -override "%1"
rundll32.exe shell32.dll,OpenAs_RunDLL "%1"
I tried to start a process using the "openas" verb and the "Open With" dialog displayed, thus will have a check box named "Always open with this application," as-if clicking "Open With" from a file's context menu. But that will open the file, and an exception is thrown for an extension with no file association set.
public static void ShowOpenWithDialog(string extension)
{
string tempPath = $"{Path.GetTempPath()}{Guid.NewGuid()}{extension}";
File.WriteAllText(tempPath, "");
using(Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
UseShellExecute = true,
FileName = tempPath,
Verb = "openas"
};
process.Start();
}
File.Delete(tempPath);
}
I want to know, how can I call the "Open With" dialog used to associate file formats? Bandizip can do it!
I found a screenshot of an English language display system that sets up file associations for specified file types in Settings, like this.

c# how to inclued a pdf file to my windows form application

When i publish my windows application for a cd/usb , i want that pdf iclueded with application. And when install the program, pdf must copied to user's computer. Then i must know the pdf file's directory for click event. What should i do?
Note: I'm sorry for my bad english. I hope that explain my problem.
Here's picture from my app;
After edited;
pdfFullPath = Path.GetFullPath("Kullanım Kılavuzu.pdf");
and my buttons like;
private void btnFirma_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(pdfFullPath);
}
As Oguz said, ensure that the PDF is included in the build path first.
If your executable is always going to be in a fixed directory structure. So you will know where the pdf is in relation to the application. You can try:
string pdfFullPath = Directory.GetCurrentDirectory() + "\\document\\Kullanım Kılavuzu.pdf";
Almost forgot your working directory might be off.
In your button click try:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = pdfFullPath;
startInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "\\document";
Process.Start(startInfo);
Right click the pdf file and click properties, then in the properties window set the following properties:
Build Action: Content
Copy to Output Directory: Copy always
After publishing your app, the file will be at this path:
string pdfFullPath = Path.GetFullPath("Kullanım Klavuzu.pdf");

forcing to close a file

I have file that another process using it.
and I want to force closing the file. so that I will work on the fill.
I tried to use Handle.exe however it didn't find the process
would appreiciate some help here is my code:
Process tool = new Process();
tool.StartInfo.FileName = handlPath;
tool.StartInfo.Arguments = _pathDirectory + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
I'm sure, that if a program really holds an exclusive access to a file, it has a reason to do it. For example, Windows Explorer holds it when the file is in copying process.
Very often, programs open a file for a writing, but do not actively write to it. For example, when you open a document in MS Word, it is copied to the temp file and a source file is just "open for writing". You'll still have an exception if you use standard File.Open method, but you can copy it to a temp file using File.Copy.
Alternatively, you can explicitly specify FileShare.ReadWrite parameter and get an access to a file. In this case, other program will have problems with accessing a file.
If you have mentioned the file name or type it would have been more easier, anyway try using the cmd for this. Get the process name and replace ProcessName.exe of the following code.
First you'll have to add using System.Diagnostics; on top.
Process.Start("cmd.exe", "/c taskkill /F /IM ProcessName.exe");

How to run "Run Bar" commands?

I need to run a command "control bthprops.cpl" in a C# program. This command brings up Bluetooth Settings control panel window. I tried running it using Process.Start() but the bluetooth window doesn't show up. I also tried writing a BAT file to the disk and executing it though my program, but still has the same problem. Is there any way to accomplish this?
//Dump BAT File and execute it
string path = System.IO.Directory.GetCurrentDirectory()+"startBT.bat";
string[] content = {"control bthprops.cpl"};
System.IO.File.WriteAllLines(path, content);
//Execute BAT file
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = path;
p.Start();
No need to go with a BAT file, this single line ought to open the specified control panel;
System.Diagnostics.Process.Start("control", "bthprops.cpl");
Since I don't have aforementioned bthprops.cpl; at least this works on W7 (open desktop settings)
System.Diagnostics.Process.Start("control", "desk.cpl");
If your control panel has tabs, you can even select what tab to open;
System.Diagnostics.Process.Start("control", "bthprops.cpl,,2");
Supply the full path and start it, for example:
var path = Path.Combine(Environment.SystemDirectory, "bthprops.cpl");
if (File.Exists(path))
{
Process.Start(path);
}

Open file by URL from WPF

I would like to programmatically open a document from a SharePoint URL.
I have the following code:
Process wordProcess = new Process();
wordProcess.StartInfo.FileName
= "http://sharepoint/blank_site_1/document library 1/word document.docx";
wordProcess.StartInfo.UseShellExecute = true;
wordProcess.Start();
This opens a webbrowser window and downloads the file, which is not what I want. If I append
wordProcess.StartInfo.Verb = "OpenAsReadOnly"
as per (the documentation) I get a Win32 Exception "The parameter is incorrect" at wordProcess.Start(), despite the verb being present in wordProcess.StartInfo.Verbs when examining in the debugger.
I have a POC which does this by extracting the default program from the registry, building a command and starting the program with the filename, but I'd rather not go down that route if this can be easily solved, as all I want to do is open a file (the path of which just happens to look like a URL) with the default program.
Just a guess, try this:
wordProcess.StartInfo.FileName = "winword.exe";
wordProcess.StartInfo.Arguments = "\"http://sharepoint/blank_site_1/document_library_1/word document file.docx\"";

Categories