Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

windows - How to associate a file extension to the current executable in C#

I'd like to to associate a file extension to the current executable in C#. This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument. Ideally it'd also set the icon for the given file extensions to the icon for my executable. Thanks all.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There doesn't appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to.

You'll need to create a key under HKEY_CLASSES_ROOT with the name set to your file extension (eg: ".txt"). Set the default value of this key to a unique name for your file type, such as "Acme.TextFile". Then create another key under HKEY_CLASSES_ROOT with the name set to "Acme.TextFile". Add a subkey called "DefaultIcon" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called "shell". Under the "shell" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and "%1" to represent the path to the file selected.

For instance, here's a sample registry file to create an association between .txt files and EmEditor:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT.txt]
@="emeditor.txt"

[HKEY_CLASSES_ROOTemeditor.txt]
@="Text Document"

[HKEY_CLASSES_ROOTemeditor.txtDefaultIcon]
@="%SystemRoot%\SysWow64\imageres.dll,-102"

[HKEY_CLASSES_ROOTemeditor.txtshell]

[HKEY_CLASSES_ROOTemeditor.txtshellopen]

[HKEY_CLASSES_ROOTemeditor.txtshellopencommand]
@=""C:\Program Files\EmEditor\EMEDITOR.EXE" "%1""

[HKEY_CLASSES_ROOTemeditor.txtshellprint]

[HKEY_CLASSES_ROOTemeditor.txtshellprintcommand]
@=""C:\Program Files\EmEditor\EMEDITOR.EXE" /p "%1""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...