Associate a file extension to an application within C# application

Refresh

December 2018

Views

1.3k time

2

I need to associate a file extension to a specific executable application and write its value in th register , so i see this tutorial : tutorial

so i create a new Wpf application in which i add this class :

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)
                        key.CreateSubKey(@"Shell\Open\Command").SetValue("",
                                    ToShortPathName(application) + " \"%1\"");
                }
        }

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

        [DllImport("Kernel32.dll")]
        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();
        }
    }

Then, i added the icon image to the root of the project and i put this snippet :

  if (!FileAssociation.IsAssociated(".akp"))
                FileAssociation.Associate(".akp", "ClassID.ProgID", "akp File", "akeo.ico", @"C:\Users\Lamloumi\Desktop\MyWork\C#\App - SuiteTool\bin\x64\Debug\App - SuiteTool.exe");

But i got a problem here in this line

Registry.ClassesRoot.CreateSubKey(extension).SetValue("", progID);

dem

So i need to know

  1. What is the problem ie why this code didn't work?
  2. How can i fix it?

Thanks,

1 answers

2

Кажется, что у вас нет достаточно прав для записи в реестре окна Попробуйте добавить к проекту app.manifest файл с содержанием:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
          <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
          </requestedPrivileges>
        </security>
      </trustInfo>
</asmv1:assembly>

или если приложение должно работать , не требуя права администратора на каждом запуске добавить возможность самостоятельно возвысить , как показано в этом примере UAC самовозвышение