1

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 を使用して特定の場所にあるファイルを開くにはどうすればよいですか?

4

1 に答える 1

4

Interaction.Shell関連付けられたドキュメントでアプリケーションを開くことができないようです。(a) 関連するMSDN ページにはそのように記載されていません (ただし、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)。

于 2012-01-18T13:49:06.093 に答える