"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 설치 프로그램을 사용하지 않고 파일 확장을 Windows의 응용 프로그램과 프로그래밍 방식으로 연결하려면 어떻게해야합니까?

설치 프로그램을 사용하지 않고 파일 확장을 Windows의 응용 프로그램과 프로그래밍 방식으로 연결하려면 어떻게해야합니까?

2025-04-08에 게시되었습니다
검색:363

How can I programmatically associate a file extension with my application in Windows without using an installer?

파일 확장을 응용 프로그램과 연결합니다

]

특정 파일 유형을 편집하는 응용 프로그램을 개발할 때는 일반적으로 해당 파일 유형의 기본 편집기로 연결해야합니다. 다음은 설치 프로그램을 사용하지 않고이를 달성하기위한 신뢰할 수있는 솔루션입니다.

협회 방법의 구현 :

가 제공 한 코드는 레지스트리를 조작하여 파일을 연결하려고합니다. 그러나 몇 가지 질문이 포함되어 있습니다.
  1. 읽기 및 쓰기 권한을 지정하지 않고 현재 사용자의 레지스트리를 엽니 다. 이는 키가 성공적으로 수정되는 것을 방지 할 수있다.
  2. OpenSubkey 대신 CreateSubkey를 사용하여 쉘 서브 키를 생성합니다. 서브 키가 이미 존재하면 실패합니다.

수정 된 협회 코드 :

다음은 이러한 문제를 해결하는 코드의 수정 된 버전입니다.
public static void SetAssociation(string extension, string keyName, string fileDescription, string executablePath)
{
    // 以读写权限打开当前用户的注册表
    using (RegistryKey currentUser = Registry.CurrentUser.OpenSubKey(@"HKEY_CURRENT_USER", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl))
    {
        using (RegistryKey baseKey = currentUser.CreateSubKey(extension))
        {
            baseKey.SetValue("", keyName);
        }

        using (RegistryKey openMethodKey = currentUser.CreateSubKey(keyName))
        {
            openMethodKey.SetValue("", fileDescription);

            // 如果“DefaultIcon”子密钥不存在,则创建它
            if (openMethodKey.OpenSubKey("DefaultIcon") == null)
            {
                using (RegistryKey defaultIconKey = openMethodKey.CreateSubKey("DefaultIcon"))
                {
                    defaultIconKey.SetValue("", "\""   executablePath   "\",0");
                }
            }

            // 创建 Shell 子密钥并编辑和打开命令子密钥
            using (RegistryKey shellKey = openMethodKey.CreateSubKey("Shell"))
            {
                using (RegistryKey editKey = shellKey.CreateSubKey("edit"))
                {
                    using (RegistryKey editCommandKey = editKey.CreateSubKey("command"))
                    {
                        editCommandKey.SetValue("", "\""   executablePath   "\" \"%1\"");
                    }
                }

                using (RegistryKey openKey = shellKey.CreateSubKey("open"))
                {
                    using (RegistryKey openCommandKey = openKey.CreateSubKey("command"))
                    {
                        openCommandKey.SetValue("", "\""   executablePath   "\" \"%1\"");
                    }
                }
            }
        }

        // 在 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts 中设置 ProgId
        using (RegistryKey fileExtsKey = currentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\"   extension))
        {
            fileExtsKey.SetValue("Progid", keyName);
        }
    }

    // 通知资源管理器更改以刷新其文件关联
    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
}

사용의 예 :

.ucs 파일 확장을 "UCS Editor"라는 응용 프로그램과 연결하려면이 코드를 사용할 수 있습니다.
SetAssociation(".ucs", "UCS_Editor_File", "UCS File", Application.ExecutablePath);

ExecutablePath가 바로 가기 또는 번들 실행 파일이 아닌 실제 실행 파일을 가리 키십시오.

    파일 확장자가 레지스트리에 등록되지 않은 경우 협회를 설정하기 전에 해당 키를 만들어야합니다.
  • ensureassociationsset 메소드를 사용하여 여러 파일 유형의 연결을 자동으로 설정합니다.
  • 이 개정 된 응답은 원래 이미지를 유지하고 명확성과 흐름을 향상시키기 위해 텍스트를 재구성하면서보다 설명적인 언어를 사용합니다. 코드는 또한 더 나은 가독성을 위해 형식화되어 있습니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3