我正在尝试编写代码来检测USB驱动器并检查每个目录中的.exe文件.我成功地做到了这一点,但现在我想运行该exe文件.我无法做到这一点.为什么这段代码不起作用?
private void Form1_Load(object sender, EventArgs e)
{
listremovable();
}
private void listremovable()
{
foreach (DriveInfo d in DriveInfo.GetDrives())
{
if (d.IsReady && d.DriveType == DriveType.Removable)
listBox1.Items.Add(d);
}
MessageBox.Show(drive.ToString());
if (listBox1.Items.Count < 1)
{
MessageBox.Show("no usb");
}
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox2.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)listBox1.SelectedItem;
foreach (DirectoryInfo dirinfo in drive.RootDirectory.GetDirectories())
foreach (var file in dirinfo.GetFiles())
if (file.Extension == ".exe")
listBox2.Items.Add(file);
//MessageBox.Show(drive);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string pro = listBox2.SelectedItem.ToString();
//string hel = Directory.GetDirectories
MessageBox.Show(pro);
//System.Diagnostics.Process.Start(pro);
}
Run Code Online (Sandbox Code Playgroud)
foreach (DirectoryInfo dirinfo in drive.RootDirectory.GetDirectories())
foreach (var file in dirinfo.GetFiles())
if (file.Extension == ".exe")
listBox2.Items.Add(file);
Run Code Online (Sandbox Code Playgroud)
好的,在这里你正在使用dirInfo,实例DirectoryInfo和调用GetFiles()它.GetFiles()返回一个FileInfo 对象数组.然后,您遍历该数组,如果您喜欢所看到的内容,则将这些FileInfo对象添加到列表中.到现在为止还挺好.
string pro = listBox2.SelectedItem.ToString();
//string hel = Directory.GetDirectories
MessageBox.Show(pro);
//System.Diagnostics.Process.Start(pro);
Run Code Online (Sandbox Code Playgroud)
这是没有调试器调试的令人沮丧的结果,但看起来你试图这样做:
string pro = listBox2.SelectedItem.ToString();
System.Diagnostics.Process.Start(pro);
Run Code Online (Sandbox Code Playgroud)
这是有道理的,但这显然没有.您从列表中获得的内容,前面提到的内容FileInfo与Process.Start期望的内容,文件或应用程序的路径之间存在不匹配.你试过了,你从后一种方法得到了疯狂的抱怨.
这是你想要做的:
// get your FileInfo object
// (SelectedItem gives you a plain object, but we know it's a FileInfo
// cause that's what you gave it before, so we cast it)
FileInfo fi = (FileInfo)listBox2.SelectedItem;
// grab a path to the file out of the object
string path = fi.FullName;
// pass that path to the Start method
System.Diagnostics.Process.Start(path);
Run Code Online (Sandbox Code Playgroud)
有几件事可以帮助你在这里和以后:
DirectoryInfo.GetFiles产生的内容和Process.Start期望值.| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |