Use the ShellExecuteEx
API with the explore
verb as documented in SHELLEXECUTEINFO
.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
private const int SW_SHOW = 5;
public static bool OpenFolderInExplorer(string folder)
{
var info = new SHELLEXECUTEINFO();
info.cbSize = Marshal.SizeOf<SHELLEXECUTEINFO>();
info.lpVerb = "explore";
info.nShow = SW_SHOW;
info.lpFile = folder;
return ShellExecuteEx(ref info);
}
Code like Process.Start("explorer.exe", folder);
is actually saying "throw the command string explorer.exe [folder] at the shell's command interpreter, and hope for the best". This might open an explorer window at the specified folder, if the shell decides that Microsoft's Windows Explorer is the program that should be run, and that it parses the (possibly unescaped) folder argument how you think it would.
In short, ShellExecuteEx
with the explore
verb is documented to do exactly what you want, while starting explorer.exe
with an argument just happens to have the same outcome, under the condition that a bunch of assumptions are true on the end-users system.
Windows Form Application
C# template in Visual Studio. – Sansone