Home >Backend Development >C++ >How to Associate Custom Executables with File Extensions in C#?

How to Associate Custom Executables with File Extensions in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-20 16:24:12923browse

How to Associate Custom Executables with File Extensions in C#?

Associating custom executable files with file types in C#

Associate a specific file extension with a custom executable file in C#, allowing the user to launch the executable file with the associated file as a parameter when clicking the file in File Explorer. Additionally, you can specify the desired icon for the file extension.

Solution

Although .NET does not provide an API to directly manage file associations, you can utilize registry classes to manipulate necessary key values.

  1. Create registry key: Create a registry key with the file extension as its name (for example, ".txt") under HKEY_CLASSES_ROOT. Set its default value to a unique name for the file type (for example, "Acme.TextFile").
  2. Create another registry key: Create a registry key under HKEY_CLASSES_ROOT with the name of the unique file type from step 1 (for example, "Acme.TextFile").
  3. Add subkey: named "DefaultIcon", whose default value is the path to the desired icon file.
  4. Add sibling item: named "shell", used to save context menu operations. For each action, a subkey is created with its default value set to the path to the executable file, followed by a space and "%1" (the file path placeholder).

Example of registry file to associate .txt with EmEditor:

<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 to Associate Custom Executables with File Extensions 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