我不需要任何界面,只需要程序是一个.exe
文件,可以打开一个目录(例如F:)。
在C#中应该使用哪种模板?除了Visual Studio以外还有更好的选择吗?或者完全使用不同的方式会更好吗?
在C#
中,您可以轻松实现这一点:
Process.Start(@"c:\users\");
当文件夹不存在时,这一行代码将抛出Win32Exception
异常。如果您使用Process.Start("explorer.exe", @"C:\folder\");
,它将只打开另一个文件夹(如果您指定的文件夹不存在)。
因此,如果您仅想在文件夹存在时打开它,应该执行以下操作:
try
{
Process.Start(@"c:\users22222\");
}
catch (Win32Exception win32Exception)
{
//The system cannot find the file specified...
Console.WriteLine(win32Exception.Message);
}
Path.DirectorySeparatorChar
是至关重要的。否则,如果同一目录中有另一个带有 .exe
或 .cmd
等扩展名的文件夹,则资源管理器将启动到该文件夹而不是您打算打开的文件夹。请参见 VS 在此方面的失败。 - binkiusing(Process.Start(@"c:\users22222\")) { }
- CBFT%SystemRoot%\explorer.exe "folder path"
class Program
{
static void Main(string[] args)
{
Process.Start("explorer.exe", @"C:\...");
}
}
使用在 ShellExecuteEx
API 中使用文档中记录的explore
动词,配合 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);
}
像这样的代码Process.Start("explorer.exe", folder);
实际上就是在告诉计算机“将命令字符串explorer.exe [folder]传递给shell的命令解释器,并希望一切顺利”。如果shell决定运行Microsoft的Windows Explorer并且按照你的想法解析(可能未转义的)文件夹参数,那么它可能会打开指定文件夹的资源管理器窗口。
简而言之,使用explore
动词的ShellExecuteEx
可以精确地完成您想要的事情,而仅仅通过启动具有参数的explorer.exe
只有在满足一系列假设的前提下才能达到相同的效果。
System.Runtime.InteropServices
。 - Simone BrognoliMarshal.SizeOf(typeof(SHELLEXECUTEINFO))
。 - AntonK希望你正在寻找 FolderBrowserDialog
,如果是这样,下面的代码将会有所帮助:
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath ;
}
如果你想通过代码打开“我的电脑”,可以使用以下选项:
string myComputerPath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
System.Diagnostics.Process.Start("explorer", myComputerPath);
Windows Form Application
_C#_模板。 - Topman