Windowsで特定のファイルタイプを開くためのデフォルトアプリケーションを見つける

StackOverflow https://stackoverflow.com/questions/162331

  •  03-07-2019
  •  | 
  •  

質問

C#を使用して.NET Framework 2.0をターゲットとするアプリケーションを開発していますが、特定のファイルタイプを開くために使用されるデフォルトアプリケーションを見つける必要があります。

たとえば、そのアプリケーションを使用してファイルを開くだけの場合、次のようなものを使用できることを知っています:

System.Diagnostics.Process.Start( "C:\...\...\myfile.html" );

デフォルトのブラウザでHTMLドキュメントを開く、または

System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" );

デフォルトのテキストエディタでテキストファイルを開く。

しかし、私ができることは、デフォルトのテキストエディタで .txt 拡張子を必ずしも持たないファイルを開くことです。そのため、 .txt ファイルを開くためのデフォルトのアプリケーションを見つけることができます。これにより、ファイルを直接呼び出すことができます。

これを行うためにP / Invokeに必要なWin32 APIがあると推測していますが、GoogleとMSDNの両方をざっと見ても、あまり興味深いものは見つかりませんでした。非常に多くの完全に無関係なページを見つけましたが、私が探しているようなものはありません。

役に立ちましたか?

解決

レジストリセクション HKEY_CLASSES_ROOT で拡張機能とアクションの詳細を確認できます。このドキュメントは、 MSDN にあります。または、 IQueryAssociations インターフェースを使用できます。

他のヒント

現在の回答はすべて信頼できません。レジストリは実装の詳細であり、実際、このようなコードはWindows 8.1マシンで壊れています。これを行う適切な方法は、Win32 API、特に AssocQueryString を使用することです。

using System.Runtime.InteropServices;

[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern uint AssocQueryString(
    AssocF flags, 
    AssocStr str,  
    string pszAssoc, 
    string pszExtra, 
    [Out] StringBuilder pszOut, 
    ref uint pcchOut
); 

[Flags]
public enum AssocF
{
    None = 0,
    Init_NoRemapCLSID = 0x1,
    Init_ByExeName = 0x2,
    Open_ByExeName = 0x2,
    Init_DefaultToStar = 0x4,
    Init_DefaultToFolder = 0x8,
    NoUserSettings = 0x10,
    NoTruncate = 0x20,
    Verify = 0x40,
    RemapRunDll = 0x80,
    NoFixUps = 0x100,
    IgnoreBaseClass = 0x200,
    Init_IgnoreUnknown = 0x400,
    Init_Fixed_ProgId = 0x800,
    Is_Protocol = 0x1000,
    Init_For_File = 0x2000
}

public enum AssocStr
{
    Command = 1,
    Executable,
    FriendlyDocName,
    FriendlyAppName,
    NoOpen,
    ShellNewValue,
    DDECommand,
    DDEIfExec,
    DDEApplication,
    DDETopic,
    InfoTip,
    QuickTip,
    TileInfo,
    ContentType,
    DefaultIcon,
    ShellExtension,
    DropTarget,
    DelegateExecute,
    Supported_Uri_Protocols,
    ProgID,
    AppID,
    AppPublisher,
    AppIconReference,
    Max
}

関連ドキュメント:

使用例:

static string AssocQueryString(AssocStr association, string extension)
{
    const int S_OK = 0;
    const int S_FALSE = 1;

    uint length = 0;
    uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length);
    if (ret != S_FALSE)
    {
        throw new InvalidOperationException("Could not determine associated string");
    }

    var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination
    ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length);
    if (ret != S_OK)
    {
        throw new InvalidOperationException("Could not determine associated string"); 
    }

    return sb.ToString();
}

Doh!もちろんです。

HKEY_CLASSES_ROOT\.txt

への参照を含む

HKEY_CLASSES_ROOT\txtfile

サブキーが含まれています

HKEY_CLASSES_ROOT\txtfile\shell\open\command

メモ帳を参照します。

ソート済み、どうもありがとう!

バート

これについてのブログ記事はこちらコードサンプルはVB.netにありますが、C#に簡単に移植できるはずです。

レジストリを照会するだけです。まず、HKEY_CLASSES_ROOT \ .ext

の下にあるデフォルトのエントリを取得します

これでクラス名がわかります。たとえば、.txtのデフォルトはtxtfileです

次に、HKEY_CLASSES_ROOT \ txtfile \ Shell \ Open \ Commandを開きます

これにより、使用されるデフォルトのコマンドが表示されます。

  

遅い回答ですが、ファイルの関連付けを処理する優れたNUGETパッケージがあります:ファイルの関連付け

リンクNUGETファイルの関連付け

使用方法は簡単です。たとえば、許可されているすべてのファイル拡張子をコンテキストメニューに追加します。

private void OnMenuSourceFileOpening(object sender, ...)
{   // open a context menu with the associated files + ".txt" files
    if (File.Exists(this.SelectedFileName))
    {
        string fileExt = Path.GetExtension(this.SelectedFileNames);
        string[] allowedExtensions = new string[] { fileExt, ".txt" };
        var fileAssociations = allowedExtensions
            .Select(ext => new FileAssociationInfo(ext));
        var progInfos = fileAssociations
            .Select(fileAssoc => new ProgramAssociationInfo (fileAssoc.ProgID));
        var toolstripItems = myProgInfos
            .Select(proginfo => new ToolStripLabel (proginfo.Description) { Tag = proginfo });
        // add also the prog info as Tag, for easy access
        //  when the toolstrip item is selected
        // of course this can also be done in one long linq statement

        // fill the context menu:
        this.contextMenu1.Items.Clear();
        this.contextMenuOpenSourceFile.Items.AddRange (toolstripItems.ToArray());
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top