1

我想使用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 在特定位置打开文件?

4

1 回答 1

4

看起来好像Interaction.Shell无法通过关联文档打开应用程序。(a) 相关的MSDN 页面没有这样说(尽管该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)。

于 2012-01-18T13:49:06.093 回答