【问题标题】:Why do I get file not found excpetion with Interaction.Shell method?为什么我使用 Interaction.Shell 方法找不到文件异常?
【发布时间】:2023-03-24 01:54:01
【问题描述】:

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

【问题讨论】:

  • Shell() 与 ProcessStartInfo.UseShellExecute = false 的 Process.Start() 相同。这意味着您只能启动可执行程序,而不能启动文档。使用 Process 类。
  • @HansPassant 我试图解决记事本在启动时像 process.Start() 一样关注焦点的问题。 VB 处理得很好。从这里得到它stackoverflow.com/questions/2121911/…。这里的回答者也解决了它。谢谢

标签: c# vb.net shellexecute interaction


【解决方案1】:

看起来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)。

【讨论】:

  • 完美解决方案。在我的 winforms 应用程序中打开它时,我遇到了记事本获取焦点的问题,例如 process.Start()。你可以在这里stackoverflow.com/questions/8881038/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2016-02-01
相关资源
最近更新 更多