Implement "Open Containing Folder" and highlight file - c#

This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:
System.Diagnostics.Process.Start( *path to folder* );
...but how do I go about actually selecting the target file within that parent folder? If I use the Process.Start method it actually attempts to open the file.

According to Windows Explorer Command-Line Options you just need to start an explorer process with /select parameter.
For instance, 'explorer /select,c:\Windows' will open a window with c:\windows folder selected.
So simply Process.Start("explorer.exe", "/select," + filename) should be enough.

Execute Explorer.exe with /select, "filename" command line argument
System.Diagnostics.Process.Start(
"explorer.exe",
string.Format("/select, \"{0}\"", filename));

Containing folder, Self directory is represented in many ways!!!
Simple 2 ways are . and, .\. no idea what is the difference!.. :D
From DOS and bat files... Start . or Start .\. (Y)
Try... these 2 works, but check whether this is the solution u expect!
System.Diagnostics.Process.Start("explorer.exe", #".\.");
Or
System.Diagnostics.Process.Start("explorer.exe", #".");
-
Sometimes the application is run from a temp directory or a different dir (eg: in Sandbox... or while being scanned by antivirus... etc. :)

Related

How to open a file's folder? C# [duplicate]

I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?
System.Diagnostics.Process.Start("explorer.exe", #"c:\teste");
Have you made sure that the folder "c:\teste" exists? If it doesn't, explorer will open showing some default folder (in my case "C:\Users\[user name]\Documents").
Update
I have tried the following variations:
// opens the folder in explorer
Process.Start(#"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", #"c:\temp");
// throws exception
Process.Start(#"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", #"c:\does_not_exist");
If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:
Open the Run dialog, enter "explorer.exe" and hit enter
Open a command prompt, type "explorer.exe" and hit enter
Just for completeness, if all you want to do is to open a folder, use this:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
FileName = "C:\\teste\\",
UseShellExecute = true,
Verb = "open"
});
Ensure FileName ends with Path.DirectorySeparatorChar to make it unambiguously point to a folder. (Thanks to #binki.)
This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
If you want to select the file or folder you can use the following:
Process.Start("explorer.exe", "/select, c:\\teste");
You're using the # symbol, which removes the need for escaping your backslashes.
Remove the # or replace \\ with \
You don't need the double backslash when using unescaped strings:
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
You should use one of the System.Diagnostics.Process.Start() overloads. It's quite simple!
If you don't place the filename of the process you want to run (explorer.exe), the system will recognize it as a valid folder path and try to attach it to the already running Explorer process. In this case, if the folder is already open, Explorer will do nothing.
If you place the filename of the process (as you did), the system will try to run a new instance of the process, passing the second string as a parameter. If the string is a valid folder, it is opened on the newly created process, if not, the new process will do nothing.
I don't know how invalid folder paths are treated by the process in any case. Using System.IO.Directory.Exists() should be enough to ensure that.
Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.
You're escaping the backslash when the at sign does that for you.
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
This code works fine from the VS2010 environment and opens the local folder properly, but if you host the same application in IIS and try to open then it will fail for sure.
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.
If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.
Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?
The following code should open a new explorer instance
class sample{
static void Main()
{
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
}
}
Do you have a lot of applications running when you are trying this?
I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000.
It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
Just change the path or declare it in a string

Program crashes when run not from own directory

A basic question:
I have a C# Windows application which runs fine when executed from its own directory, by typing
program1.exe
but when I execute it from another directory giving full path like
d:/progs/myprog/program1.exe
it crashes. And I really need to do it this way :)
I suppose it is connected to reading some files by the program which are in the same directory. My suspected line is:
using (XmlReader OdczytywaczXML = XmlReader.Create(#"config.xml"))
Can it be the problem? I wouldn't like to give full paths to files as I'd like my program to work anywhere just by copying the files.
Oh, and I have no idea how to simulate such condition (running from another directory) while debugging - is it possible?
You should detect your program location and construct full path to config.xml in this case, for example:
var filePath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
#"config.xml");
To simulate condition, go to project properties, page "Debug" and set Working Directory.
This is surely the problem. You can add directory information on that line. In WinForms you can use Application.StartupPath for example.
In General you can use System.Reflection.Assembly.GetExecutingAssembly().Location
The issue is that the Working Directory isn't the same when you just execute it from the command-line. You'll want to safeguard this:
var path = Path.Combine(Assembly.GetExecutingAssembly().Location, "config.xml");
using (XmlReader OdczytywaczXML = XmlReader.Create(path))
The Location property will do the following for you:
Gets the full path or UNC location of the loaded file that contains the manifest.
One thing to note here is that if you added a shortcut to the Desktop and set the Working Directory, before changing the code, you would find the application runs fine. Do that first to verify the fix worked.

silently execute a MSI package from C#

Newbie question, let me try and make this as clear as possible. I have a program that needs to silently execute a msi package (well multiple but that's not the problem)
The MSI packages are contained in a folder located in the same directory as my program. I've given it a simple name of "InstallFiles" for the time being.
I'm not keen on using the full path name eg. C:\my program\another directory\another directory etc because it'll be put on multiple PC's, old and new, in which case the drive letter can change. So far I have:
install.StartInfo.FileName = "msiexec";
install.StartInfo.Arguments = "/i F:\\InstallFiles\\JRE.msi";
install.Start();
install.WaitForExit();
However, when its launched it only gives me the Windows Installer switch information and then terminates, how do I get it to run and how would I go about changing the file path?
use with the following switch:
/q[n|b|r|f]
Sets user interface level
n - No UI
b - Basic UI
r - Reduced UI
Check http://msdn.microsoft.com/en-us/library/windows/desktop/aa367988%28v=vs.85%29.aspx for detailed commandline options.
The executing of .msi file should be like .exe file that here is your answer : https://stackoverflow.com/a/12436300/359170
start the application with this code :
Process.Start("yourfile.msi");
and it don't need the full path, it adds current directory to the file name you written there.
But
System.IO.Directory.GetCurrentDirectory();
gets the current executed file directory. And you can get the file path by adding just the name of the file to it like this :
string path = System.IO.Directory.GetCurrentDirectory() + "\\yourfile.msi";

Include a batch file in a batch file

I have a problem calling a batch file from another batch file when trying to run everything by using Process.Start. Basically I call the execution of a batch file from my c# program that looks like this:
call include.bat
//execute the rest of the batch file here
The include.bat file sets up paths and can be used by a number of other batch files. When I run the Process.Start sometimes this works and sometimes I get ERROR: cannot find include.bat. First of all any idea why this happens? And ideas on how to fix this from the batch file?
To switch to the directory your batch file is located in, use this:
cd %~dp0
I do this in almost all of my batch scripts. That way relative paths should always work.
I know this is an old question but I thought it would be worth noting that the approach promoted by the accepted answer (i.e. changing the working directory) may not always be appropriate.
A better general approach is to refer to dependencies by full path:
call "%~dp0include.bat"
(Since %~dp0 already ends with a backslash, we don't need to add another one.)
Here are some benefits of not changing the working directory:
The rest of the batch file can still use the original working directory.
The original working directory in the command prompt is preserved, even without "SETLOCAL".
If the first batch file is run via a UNC path (such as "\\server\share\file.bat"), the full-path call will succeed while changing the directory (even with "cd /d") will fail. (Using pushd/popd would handle this point, but they have their own set of problems.)
These benefits are particularly important for alias-type batch files, even if they are not as important for the specific situation that motivated this question.
Before the script, try CD /D %~dp0
First thing I'd try is to use full path information in the call statement for include.bat. If that fixes it, you probably are just not running the batch file from the proper location. I'm sure there's a "working directory" capability in C#, I'm just not sure what it is.
Do you set ProcessStartInfo.WorkingDirectory ( http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx ) on the ProcessStartInfo that you pass to Process.Start?
Since include.bat sometimes cannot be found, working directory may be wrong (not the folder where include.bat is located).

Open a folder using Process.Start

I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?
System.Diagnostics.Process.Start("explorer.exe", #"c:\teste");
Have you made sure that the folder "c:\teste" exists? If it doesn't, explorer will open showing some default folder (in my case "C:\Users\[user name]\Documents").
Update
I have tried the following variations:
// opens the folder in explorer
Process.Start(#"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", #"c:\temp");
// throws exception
Process.Start(#"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", #"c:\does_not_exist");
If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:
Open the Run dialog, enter "explorer.exe" and hit enter
Open a command prompt, type "explorer.exe" and hit enter
Just for completeness, if all you want to do is to open a folder, use this:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
FileName = "C:\\teste\\",
UseShellExecute = true,
Verb = "open"
});
Ensure FileName ends with Path.DirectorySeparatorChar to make it unambiguously point to a folder. (Thanks to #binki.)
This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
If you want to select the file or folder you can use the following:
Process.Start("explorer.exe", "/select, c:\\teste");
You're using the # symbol, which removes the need for escaping your backslashes.
Remove the # or replace \\ with \
You don't need the double backslash when using unescaped strings:
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
You should use one of the System.Diagnostics.Process.Start() overloads. It's quite simple!
If you don't place the filename of the process you want to run (explorer.exe), the system will recognize it as a valid folder path and try to attach it to the already running Explorer process. In this case, if the folder is already open, Explorer will do nothing.
If you place the filename of the process (as you did), the system will try to run a new instance of the process, passing the second string as a parameter. If the string is a valid folder, it is opened on the newly created process, if not, the new process will do nothing.
I don't know how invalid folder paths are treated by the process in any case. Using System.IO.Directory.Exists() should be enough to ensure that.
Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.
You're escaping the backslash when the at sign does that for you.
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
This code works fine from the VS2010 environment and opens the local folder properly, but if you host the same application in IIS and try to open then it will fail for sure.
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.
If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.
Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?
The following code should open a new explorer instance
class sample{
static void Main()
{
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
}
}
Do you have a lot of applications running when you are trying this?
I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000.
It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
Just change the path or declare it in a string

Categories