Associating a file extension with an executable file in C#
After associating a file extension with the current executable, users can open the file in Explorer and automatically run your program using the file as an argument. This article will guide you on how to do this in C# by manipulating registry keys.
Solution:
While C# lacks a dedicated API for managing file associations, you can take advantage of registry manipulation capabilities. This process involves modifying a specific key in the registry:
Example:
The following registry file associates the .txt file with EmEditor, sets the icon and defines open and print operations:
<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>
By implementing these registry modifications, you can successfully associate file extensions with executable files, providing a seamless user experience for opening and interactively using the file.
The above is the detailed content of How to Associate a File Extension with Your C# Executable?. For more information, please follow other related articles on the PHP Chinese website!