Why do I get file not found excpetion with Interaction.Shell method?

早过忘川 提交于 2019-12-11 07:37:46

问题


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);

But this works:

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

Which just opens a notepad file. Why is this?

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?


回答1:


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.

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();
}

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

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);

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).



来源:https://stackoverflow.com/questions/8911007/why-do-i-get-file-not-found-excpetion-with-interaction-shell-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!