1

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?

vcsjones
  • 138,677
  • 31
  • 291
  • 286
nawfal
  • 70,104
  • 56
  • 326
  • 368
  • Shell() is the same thing as Process.Start() with ProcessStartInfo.UseShellExecute = false. Which means you can only start executable programs, not documents. Use the Process class. – Hans Passant Jan 18 '12 at 14:48
  • @HansPassant I was trying to cover the same problem of Notepad taking the focus when starting it like process.Start(). VB handles it so well. Got it from here http://stackoverflow.com/questions/2121911/starting-a-process-without-stealing-focus-c .Also solution by the answerer here tackles it. Thanks – nawfal Jan 18 '12 at 15:18

1 Answers1

4

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

Christian.K
  • 47,778
  • 10
  • 99
  • 143
  • Perfect solution. I have a problem of Notepad taking the focus when opening it like process.Start() from my winforms app. Which you can catch here http://stackoverflow.com/questions/8881038/how-to-set-focus-back-to-form-after-opening-up-a-process-notepad – nawfal Jan 18 '12 at 15:19