我不需要任何类型的界面。我只需要将程序作为.exe
文件打开目录(例如F:)。
我会在C#中使用哪种模板?除Visual Studio之外的其他东西会更好吗?一个不同的过程会完全更好地运作吗?
答案 0 :(得分:8)
创建批处理文件,例如open.bat
并写下这一行
%SystemRoot%\explorer.exe "folder path"
如果你真的想用C#
做 class Program
{
static void Main(string[] args)
{
Process.Start("explorer.exe", @"C:\...");
}
}
答案 1 :(得分:8)
在C#
中你可以做到这一点:
Process.Start(@"c:\users\");
当文件夹不存在时,此行将抛出Win32Exception
。如果您使用Process.Start("explorer.exe", @"C:\folder\");
,它只会打开另一个文件夹(如果您指定的文件夹不存在)。
因此,如果你想打开 ONLY 文件夹,你应该这样做:
try
{
Process.Start(@"c:\users22222\");
}
catch (Win32Exception win32Exception)
{
//The system cannot find the file specified...
Console.WriteLine(win32Exception.Message);
}
答案 2 :(得分:1)
将 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)]
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 [文件夹] 扔到 shell 的命令解释器中,并希望得到最好的结果”。这可能会在指定的文件夹中打开一个资源管理器窗口,如果 shell 决定 Microsoft 的 Windows Explorer 是应该运行的程序,并且它解析(可能未转义的)文件夹参数,你认为它会如何.
简而言之,带有 ShellExecuteEx
动词的 explore
被记录为完全按照您的意愿行事,而以参数开头的 explorer.exe
恰好具有相同的结果,条件是一系列假设在最终用户系统上是正确的。
答案 3 :(得分:0)
希望您正在寻找FolderBrowserDialog
,如果是这样,以下代码可以帮助您:
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath ;
}
否则,如果您想通过代码打开Mycomputer,那么以下选项可以帮助您:
string myComputerPath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
System.Diagnostics.Process.Start("explorer", myComputerPath);