Open Windows Explorer to a Specific Path in C#

 
 
  • Gérald Barré

Sometimes, you need to open Windows Explorer to a specific folder from your C# application. This can be useful for improving user experience, providing quick access to files, or integrating with other tools. In this post, I'll show you how to achieve this using the Windows Shell API via the Microsoft.Windows.CsWin32 package, and discuss an alternative using Meziantou.Framework.FullPath.

To use Windows Shell functions in C#, you need to add the Microsoft.Windows.CsWin32 package to your project. This package provides P/Invoke bindings for many Windows APIs.

Shell
dotnet add package Microsoft.Windows.CsWin32

Alternatively, you can add the package reference directly in your project file:

Project.csproj (csproj (MSBuild project file))
<ItemGroup>
  <PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.183">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>

Then, add the following content to the the NativeMethods.txt file:

ILFree
ILCreateFromPathW
SHOpenFolderAndSelectItems

You can now use the following method to opens Windows Explorer to a given path using the generated P/Invoke methods:

C#
[SupportedOSPlatform("windows5.1.2600")]
public unsafe void OpenInExplorer(string path)
{
    if (string.IsNullOrEmpty(path))
        throw new ArgumentException("Path cannot be null or empty.", nameof(path));

    var itemList = PInvoke.ILCreateFromPath(Path.GetFullPath(path));
    if (itemList != null)
    {
        try
        {
            PInvoke.SHOpenFolderAndSelectItems(itemList, 0u, apidl: null, 0u).ThrowOnFailure();
        }
        finally
        {
            PInvoke.ILFree(itemList);
        }
    }
}

#Alternative: Using Meziantou.Framework.FullPath

For a simpler and more reusable approach, you can use the Meziantou.Framework.FullPath NuGet package which provides the similar method and simplifies path manipulations:

C#
var fullPath = FullPath.FromPath(path);
fullPath.OpenInExplorer();

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub