我想使用 VisualBasic.Interaction.Shell 方法打开一个记事本文件。目前,我使用以下代码得到一个找不到文件的异常。
int pid = Interaction.Shell(@"D:\abc.txt", AppWinStyle.NormalNoFocus, false, -1);
但这行得通:
int pid = Interaction.Shell(@"notepad.exe", AppWinStyle.NormalNoFocus, false, -1);
这只是打开一个记事本文件。为什么是这样?
我确实需要它来打开特定位置的文件。我看到了 Interaction.Shell 执行的一些优势。如何使用 Interaction.Shell 打开特定位置的文件?
请您参考如下方法:
看起来 Interaction.Shell 无法通过关联的文档打开应用程序。 (a) 相关MSDN page并没有这么说(尽管 PathName 参数的示例在那时似乎具有误导性)和 (b) 即使 D:\abc.txt 确实存在,它也会失败。
或者您可以使用 System.Diagnostics.Process类:
using (Process process = Process.Start(@"D:\abc.txt"))
{
int pid = process.Id;
// Whether you want for it to exit, depends on your needs. Your
// Interaction.Shell() call above suggests you don't. But then
// you need to be aware that "pid" might not be valid when you
// you look at it, because the process may already be gone.
// A problem that would also arise with Interaction.Shell.
// process.WaitForExit();
}
请注意 D:\abc.txt 必须存在,否则您仍然会得到一个 FileNotFoundException。
更新如果你确实需要使用Interaction.Shell,你可以使用下面的
int pid = Interaction.Shell(@"notepad.exe D:\abc.txt", false, -1);
就我个人而言,我会选择 Process 类,因为它通常对启动的进程提供更稳健的处理。在这种情况下,它还使您不必“知道”哪个程序与 .txt 文件关联(除非您总是想使用 notepad.exe)。
