How can I open a folder in Windows Explorer?
Asked Answered
T

5

11

I don't need any kind of interface. I just need the program to be an .exe file that opens a directory (eg. F:).

What kind of template would I use in C#? Would something other than Visual Studio work better? Would a different process entirely work better?

Teacake answered 4/9, 2015 at 9:57 Comment(1)
You would probably used Windows Form Application C# template in Visual Studio.Sansone
G
26

In C# you can do just that:

Process.Start(@"c:\users\");

This line will throw Win32Exception when folder doesn't exists. If you'll use Process.Start("explorer.exe", @"C:\folder\"); it will just opened another folder (if the one you specified doesn't exists).

So if you want to open the folder ONLY when it exists, you should do:

try
{
    Process.Start(@"c:\users22222\");
}
catch (Win32Exception win32Exception)
{
    //The system cannot find the file specified...
    Console.WriteLine(win32Exception.Message);
}
Gorgonian answered 4/9, 2015 at 10:11 Comment(3)
Note that if you use this answer, the suffixed Path.DirectorySeparatorChar is critical. Otherwise, if there is another folder in the same directory with an extension such as .exe or .cmd, explorer will launch to that other folder instead of the one you intended to open. See how VS fails at this.Rorke
For .NET Core 3.0+ this will throw an exception, because UseShellExecute property is false by default. Use solution as suggested hereFateful
Don't forget to call dispose on the Process using(Process.Start(@"c:\users22222\")) { }Helms
P
9

Create a batch file , for example open.bat

And write this line

%SystemRoot%\explorer.exe "folder path"

If you really want to do it in C#

  class Program
{
    static void Main(string[] args)
    {
        Process.Start("explorer.exe", @"C:\...");
    }
 }
Phosphorous answered 4/9, 2015 at 10:2 Comment(1)
You can remove all the superfluous information about the batch file, as clearly the OP wants to open it using C#.Arthrospore
L
4

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.

Leone answered 25/1, 2021 at 14:26 Comment(2)
Very precise answer. Little note: needs to include System.Runtime.InteropServicesChipman
use Marshal.SizeOf(typeof(SHELLEXECUTEINFO)) when targeting .NET Framework earlier than ~4.5Thermoplastic
D
2

Hope that you are looking for FolderBrowserDialog if so, following code will help you:

string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
    folderPath = folderBrowserDialog1.SelectedPath ;
}

Or else if you want to open Mycomputer through code, then following option will help you:

string myComputerPath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
System.Diagnostics.Process.Start("explorer", myComputerPath);
Demodulate answered 4/9, 2015 at 10:5 Comment(0)
S
1

The answer from Dialer got me curious, so I did some digging into the source code of System.Diagnostics. It turns out that System.Diagnostics.Process.Start actually has built-in support for executing Win32 ShellExecuteEx calls. You can see this in the source code here: https://github.com/dotnet/runtime/blob/4555974d1ad1baae3675beb9293696b6233cf0e0/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs#L25

The following code is likely the preferred way of opening a folder with Windows Explorer without directly using Win32 calls.

try
{
    ProcessStartInfo startInfo = new(@"C:\Some folder")
    {
        UseShellExecute = true,
        Verb = "explore"
    };

    Process.Start(startInfo);
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

(Note: the default value for UseShellExecute is true for .NET Framework and false for .NET.)

Shalom answered 22/7 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.