Search code examples
c#registry

Change default application for .txt


After a lot of searching on the internet without any success, I'm looking here for some help.

The problem seems to be quiet simple, but unfortunately I'm not able to solve it.

I want to change the default-application to open .txt-files. For example instead of using notepad I want to use Wordpad which is located at C:\Program Files\Windows NT\Accessories\wordpad.exe

So I've tried to change the registry at: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\OpenWithProgids with no success.

I've also found a solution which tries to change the group policy. This code looks like:

string tempFile = Path.GetTempFileName();
string xmlFile = tempFile.Replace(".tmp", ".xml");
File.Move(tempFile, xmlFile);

XDocument document = new XDocument(new XElement("DefaultAssociations",
    new XElement("Association",
        new XAttribute("Identifier", ".txt"),
        new XAttribute("ProgId", "txtFile"),
        new XAttribute("ApplicationName", "Editor"))));
document.Save(xmlFile);

ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\Software\Policies\Microsoft\Windows\System!DefaultAssociationsConfiguration",
    xmlFile, RegistryValueKind.String);

But this also doesn't work.

I also tried to use the command-line with ftype but that also didn't work.

Can anybody tell me how to change the assoziated application for a given filetype?


Solution

  • I guess you want to this because you have some kind of Set as default option in your program, by the way I have spent the last hour trying to figure out why it doesn't work and here it is what I've found so far.

    The step you need to take are the following:

    • Creates a registry key in ClassesRoot for the .custom extension. (Period is important)

    Code:

    Registry.ClassesRoot.CreateSubKey(".custom").SetValue("", "customfile", Microsoft.Win32.RegistryValueKind.String);`
    
    • Creating the "Customfile" sub-key and the "customfile\open\command" subkey that is needed to store the path to the application that will open this file type.

    Code:

    Registry.ClassesRoot.CreateSubKey("Customfile\shell\open\command").SetValue("", PATH_TO_YOUR_EXE, Microsoft.Win32.RegistryValueKind.String);
    

    And now the association has been made, your app will be registered as one of those which can open that extention.


    The case of .txt (or other already associated extentions)

    After messing a little bit around i found out that in order to do changes to an already associated extention you also need to edit the registry

    Example (with .txt ext.)

     HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\UserChoice
    

    This key has an ProgId value which actually contains the default application set by the user, the value is a string. So you will also have do edit/delete this Registry as well.

    I hope it helps :)!