Home >Backend Development >C++ >How Can I Programmatically Associate File Extensions with Executables in C#?

How Can I Programmatically Associate File Extensions with Executables in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-20 16:14:14429browse

How Can I Programmatically Associate File Extensions with Executables in C#?

Associating a file extension with an executable file in C#

C# itself does not have a built-in API to manage file associations. However, you can leverage the Registry API to access and modify the Windows registry because file association information is stored in the registry.

To associate a specific file extension with your executable, you need to create a registry key under HKEY_CLASSES_ROOT.

  1. Create a subkey of file extension:

    • Create a subkey under HKEY_CLASSES_ROOT named with the file extension (e.g., .txt).
    • Set the default value of this subkey to a unique name for your file type, such as "Acme.TextFile".
  2. Create file type subkey:

    • Create a subkey under HKEY_CLASSES_ROOT with the name used in the previous step (for example, "Acme.TextFile").
  3. Set default icon:

    • Add a subkey named "DefaultIcon" under the file type subkey.
    • Set the default value of "DefaultIcon" to the path and index of the icon to use.
  4. Add context menu action:

    • Create a subkey named "shell" under the file type subkey.

    • Under the "shell" subkey, create subkeys for each context menu action you want to add.

    • Sets the default value of each action subitem to the following string:

      • "executable_path" "%1"
      • Replace "executable_path" with the path to the executable file and "%1" with the placeholder for the file path passed as argument.

For example, to associate a .txt file with EmEditor, you need to create the following registry key:

<code>[HKEY_CLASSES_ROOT\.txt]
@="emeditor.txt"

[HKEY_CLASSES_ROOT\emeditor.txt]
@="Text Document"

[HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon]
@="%SystemRoot%\SysWow64\imageres.dll,-102"

[HKEY_CLASSES_ROOT\emeditor.txt\shell]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\open]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command]
@="\"C:\Program Files\EmEditor\EMEDITOR.EXE\" \"%1\""

[HKEY_CLASSES_ROOT\emeditor.txt\shell\print]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command]
@="\"C:\Program Files\EmEditor\EMEDITOR.EXE\" /p \"%1\""</code>

The above is the detailed content of How Can I Programmatically Associate File Extensions with Executables in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn