为什么我使用 Interaction.Shell 方法获取文件未找到异常? [英] Why do I get file not found excpetion with Interaction.Shell method?

查看:42
本文介绍了为什么我使用 Interaction.Shell 方法获取文件未找到异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 VisualBasic.Interaction.Shell 方法打开记事本文件.目前我使用下面的代码得到一个文件未找到异常.

I want to open a notepad file using VisualBasic.Interaction.Shell method. At present I get a file not found exception using the following code.

int pid = Interaction.Shell(@"D:\abc.txt", AppWinStyle.NormalNoFocus, false, -1);

但这有效:

int pid = Interaction.Shell(@"notepad.exe", AppWinStyle.NormalNoFocus, false, -1);

这只是打开一个记事本文件.为什么是这样?

Which just opens a notepad file. Why is this?

我确实需要它来在特定位置打开文件.我看到了 Interaction.Shell 执行的一些优势.如何使用 Interaction.Shell 在特定位置打开文件?

I do need it to open a file in a specific location. I see some advantage with Interaction.Shell execution. How is it possible to open a file in a specific location using Interaction.Shell?

推荐答案

看起来好像 Interaction.Shell 无法通过关联文档打开应用程序.(a) 相关的MSDN 页面 没有这样说(尽管 PathName 参数的示例当时似乎具有误导性)和 (b) 即使 D:\abc.txt 确实存在,它失败了.

It looks as if Interaction.Shell cannot open an application by an associated document. (a) the relevant MSDN page does not say so (although the example for the PathName parameter seems missleading then) and (b) even if D:\abc.txt does exist, it fails.

或者,您可以使用 System.Diagnostics.流程类:

Alternatively you can use the System.Diagnostics.Process class:

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.

Note that D:\abc.txt must exist, or you still get a FileNotFoundException.

更新如果你确实需要使用Interaction.Shell,你可以使用下面的

Update If you really do need to use Interaction.Shell, you can use the following

int pid = Interaction.Shell(@"notepad.exe D:\abc.txt", false, -1);

就个人而言,我会使用 Process 类,因为它通常为启动的进程提供更可靠的处理.在这种情况下,它还使您无需知道"哪个程序与 .txt 文件相关联(除非您总是想使用 notepad.exe).

Personally, I would go with the Process class, as it generally provides more robus handling of the launched process. In this case it also frees you from "knowing" which program is associated with .txt files (unless you always want to use notepad.exe).

这篇关于为什么我使用 Interaction.Shell 方法获取文件未找到异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆