nawfal
nawfal

Reputation: 73253

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

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?

Upvotes: 1

Views: 4389

Answers (1)

Christian.K
Christian.K

Reputation: 49290

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

Upvotes: 4

Related Questions