Tag Archive FileType


C#: Set File Type Association

While searching for some simple C# code to set the program and icon associated with a file type in Windows I ran across these beautiful functions that illustrate how to accomplish this by using the registry.

All credit goes to cristiscu (source).

Here’s the code:

using Microsoft.Win32;
using System.Runtime.InteropServices;

public class FileAssociation
    // Associate file extension with progID, description, icon and application
    public static void Associate(string extension, 
           string progID, string description, string icon, string application)
        Registry.ClassesRoot.CreateSubKey(extension).SetValue("", progID);
        if (progID != null && progID.Length > 0)
            using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(progID))
                if (description != null)
                    key.SetValue("", description);
                if (icon != null)
                    key.CreateSubKey("DefaultIcon").SetValue("", ToShortPathName(icon));
                if (application != null)
                                ToShortPathName(application) + " \"%1\"");

    // Return true if extension already associated in registry
    public static bool IsAssociated(string extension)
        return (Registry.ClassesRoot.OpenSubKey(extension, false) != null);

    private static extern uint GetShortPathName(string lpszLongPath, 
        [Out] StringBuilder lpszShortPath, uint cchBuffer);

    // Return short path format of a file name
    private static string ToShortPathName(string longName)
        StringBuilder s = new StringBuilder(1000);
        uint iSize = (uint)s.Capacity;
        uint iRet = GetShortPathName(longName, s, iSize);
        return s.ToString();

And here’s how you’d use it:

if (!FileAssociation.IsAssociated(".ext"))
   Associate(".ext", "ClassID.ProgID", "ext File", "YourIcon.ico", "YourApplication.exe");

A couple caveats to this code that I’ve noticed:

  1. The second parameter passed to Associate() can be any string you’d like to use to represent your program in the registry, just make sure you’re consistent with it.
  1. ToShortPathName() will return an empty string if the file path you pass it doesn’t exist, i.e. if you pass it a path to an icon file that doesn’t exist it won’t work.
  1. IsAssociated() will return true if the file extension is associated with any program, not just yours. If you want to be specific about it checking whether it’s associated with your program, then just check whether it’s default key is set to your programs ProgID.