You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过cmd/PowerShell或C#打开资源管理器并选中长路径文件

解决方案

方案1:C# 原生实现(推荐,无需调用外部进程,完美支持长路径)

直接调用Windows Shell原生API实现,是稳定性、兼容性最好的方案,完全适配.NET Framework 4.7.2运行环境:

using System;
using System.Runtime.InteropServices;
using System.IO;

public static class ExplorerHelper
{
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
    private static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, IntPtr[] apidl, uint dwFlags);

    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr ILCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath);

    [DllImport("shell32.dll")]
    private static extern void ILFree(IntPtr pidl);

    public static void OpenFolderAndSelectItem(string targetPath)
    {
        // 自动适配长路径,支持\\?\前缀格式
        string fullPath = Path.GetFullPath(targetPath);
        if (!fullPath.StartsWith(@"\\?\") && fullPath.Length >= 260)
        {
            fullPath = @"\\?\" + fullPath;
        }
        
        IntPtr pidl = ILCreateFromPath(fullPath);
        if (pidl == IntPtr.Zero)
        {
            throw new FileNotFoundException("目标路径不存在", targetPath);
        }
        
        try
        {
            SHOpenFolderAndSelectItems(pidl, 0, null, 0);
        }
        finally
        {
            ILFree(pidl);
        }
    }
}

// 调用示例
// ExplorerHelper.OpenFolderAndSelectItem(@"C:\超长路径\...\目标文件.txt");

优势:

  • 原生支持最长32767字符的长路径,完全兼容\\?\前缀格式
  • 无需启动cmd/PowerShell进程,执行效率高
  • 不会出现跳转到「此电脑」的异常问题

方案2:PowerShell 兼容方案(如果必须通过PowerShell调用)

避开explorer /select的参数解析缺陷,通过Shell COM对象实现功能:

$targetPath = "你的目标完整路径"
$fullPath = [System.IO.Path]::GetFullPath($targetPath)
$shell = New-Object -ComObject Shell.Application
$parentPath = Split-Path $fullPath -Parent
$itemName = Split-Path $fullPath -Leaf
$folder = $shell.NameSpace($parentPath)
$targetItem = $folder.ParseName($itemName)
# 1表示选中目标并激活资源管理器窗口
$folder.SelectItem($targetItem, 1)

优势:不需要处理路径引号、前缀适配问题,完美支持长路径场景。


避坑说明

explorer.exe /select参数本身不支持\\?\前缀的长路径格式,且对超过260字符的普通路径存在原生解析缺陷,无论怎么调整引号、前缀格式都无法解决,长路径场景下不建议使用该命令。

内容的提问来源于stack exchange,提问作者kirgod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:54:03