.net c# 打开目录的方法很多
1. 通用方法,可打开目录和文件.但无法选中目录中的文件.
/// <summary>
/// 打开目录或者文件,简洁写法
/// </summary>
/// <param name="filepath"></param>
public static void OpenFileTo(string filepath)
{
System.Diagnostics.Process.Start("explorer.exe", filepath);
}
2.打开指定的目录.
/// <summary>
/// 打开目录
/// </summary>
/// <param name="path">目录路径</param>
public static void OpenFolder(string path)
{
if (string.IsNullOrEmpty(path)) return;
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
psi.Arguments = path;
process.StartInfo = psi;
try
{
process.Start();
}
finally { process?.Close(); }
}
3.打开指定的目录并选中指定的文件
/// <summary>
/// 打开目录且选中文件
/// </summary>
/// <param name="filepath">文件的路径</param>
public static void OpenFolderChkFile(string filepath)
{
if (string.IsNullOrEmpty(filepath)) return;
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
psi.Arguments = "/e,/select," + filepath;
process.StartInfo = psi;
try
{
process.Start();
}
finally { process?.Close(); }
}
4.打开指定的文件
/// <summary>
/// 打开文件
/// </summary>
/// <param name="filepath">文件的路径</param>
public static void OpenFile(string filepath)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(filepath);
process.StartInfo = psi;
process.StartInfo.UseShellExecute = true;
try
{
process.Start();
}
finally { process?.Close(); }
}
5.针对部分有特殊符号的,如果需要打开目录,并选中文件
[DllImport("shell32.dll", ExactSpelling = true)]
private static extern void ILFree(IntPtr pidlList);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern IntPtr ILCreateFromPathW(string pszPath);
[DllImport("shell32.dll", ExactSpelling = true)]
private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
/// <summary>
/// 打开路径并定位文件...对于@"c:\aa\A Report - Call ??.mav"这样的,explorer.exe /select,d:xxx不认,用API调整下
/// 打开文件夹并定位到指定的文件选中,方法加强版,主要是应对路径中含有特殊字符的情况
/// </summary>
/// <param name="filepath"></param>
public static void OpenFileStrong(string filepath)
{
if (!File.Exists(filepath) && !Directory.Exists(filepath))
return;
if (Directory.Exists(filepath)) Process.Start(@"explorer.exe", "/select,\"" + filepath + "\"");
else
{
IntPtr pidlList = ILCreateFromPathW(filepath);
if (pidlList != IntPtr.Zero)
{
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
}
}
部分演示效果图如下: