Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 3개 있습니다.)
.NET Framework: 584. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본
; https://www.sysnet.pe.kr/2/0/10966

.NET Framework: 585. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
; https://www.sysnet.pe.kr/2/0/10967

.NET Framework: 586. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록
; https://www.sysnet.pe.kr/2/0/10969




C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본

특정 확장자와 응용 프로그램을 연결하는 방법은 레지스트리를 통해서 이뤄집니다. 다음의 글에도 잘 나오는데요.

Create registry entry to associate file extension with application in C++
; http://stackoverflow.com/questions/1387769/create-registry-entry-to-associate-file-extension-with-application-in-c

이번 글에서는 가장 단순한 방법만 설명할텐데, 그러니까 아래와 같이 딱 2개의 레지스트리만 등록해 주면 됩니다.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command]
@="c:\path\to\app.exe \"%1\""

[HKEY_CURRENT_USER\Software\Classes\.blerg]
@="blergcorp.blergapp.v1"

C# 코드로 보면 대략 다음과 같이 구현해 줄 수 있습니다.

using System.IO;
using Microsoft.Win32;

namespace YourExtRegister
{
    class Program
    {
        static string ext = ".1myext";
        static string fileTypeDesc = "my ext sample";
        static string extType = "yourext" + ext + ".v1";
        static string assocExeFileName = "YourExt.exe";

        static void Main(string[] args)
        {
            bool register = true;

            if (args.Length >= 1)
            {
                if (args[0] == "-u")
                {
                    register = false;
                }
            }

            ProcessFileExtReg(register);
        }

        private static void ProcessFileExtReg(bool register)
        {
            using (RegistryKey classesKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes", true))
            {
                if (register == true)
                {
                    using (RegistryKey extKey = classesKey.CreateSubKey(ext))
                    {
                        extKey.SetValue(null, extType);
                    }

                    // or, use Registry.SetValue method
                    using (RegistryKey typeKey = classesKey.CreateSubKey(extType))
                    {
                        typeKey.SetValue(null, fileTypeDesc);
                        using (RegistryKey shellKey = typeKey.CreateSubKey("shell"))
                        {
                            using (RegistryKey openKey = shellKey.CreateSubKey("open"))
                            {
                                using (RegistryKey commandKey = openKey.CreateSubKey("command"))
                                {
                                    string assocExePath = GetProcessPath();
                                    string assocCommand = string.Format("\"{0}\" \"%1\"", assocExePath);

                                    commandKey.SetValue(null, assocCommand);
                                }
                            }
                        }
                    }
                }
                else
                {
                    DeleteRegistryKey(classesKey, ext, false);
                    DeleteRegistryKey(classesKey, extType, true);
                }
            }
        }

        private static void DeleteRegistryKey(RegistryKey classesKey, string subKeyName, bool deleteAllSubKey)
        {
            if (CheckRegistryKeyExists(classesKey, subKeyName) == false)
            {
                return;
            }

            if (deleteAllSubKey == true)
            {
                classesKey.DeleteSubKeyTree(subKeyName);
            }
            else
            {
                classesKey.DeleteSubKey(subKeyName);
            }
        }

        private static bool CheckRegistryKeyExists(RegistryKey classesKey, string subKeyName)
        {
            RegistryKey regKey = null;

            try
            {
                regKey = classesKey.OpenSubKey(subKeyName);
                return regKey != null;
            }
            finally
            {
                if (regKey != null)
                {
                    regKey.Close();
                }
            }
        }

        private static string GetProcessPath()
        {
            string path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
            return Path.Combine(path, assocExeFileName);
        }
    }
}

참고로, 레지스트리가 아닌 윈도우 제어판에서 "Default Programs"를 선택해 "Associate a file type or protocol with a program" 링크를 통해서도 다음과 같이 확인할 수 있습니다.

yourext_sample_1.png

이제부터는, (예제에서는 확장자가 .1myext 이므로) test.1myext와 같은 파일을 탐색기에서 더블 클릭하면 등록된 EXE 프로그램이 실행됩니다. 그리고, 그 프로그램에서는 넘겨진 인자 정보를 통해 파일을 처리해 주시면 됩니다.

using System.Windows.Forms;

namespace YourExt
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            MessageBox.Show("Viewer Runs: " + args[0]);
        }
    }
}

(첨부한 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/12/2016]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-08-18 09시32분
정성태

... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...
NoWriterDateCnt.TitleFile(s)
10971정성태5/19/201620436오류 유형: 334. Visual Studio - 빌드 시 경고 warning MSB3884: Could not find rule set file "...". [2]
10970정성태5/19/201624841오류 유형: 333. OxyPlot 라이브러리의 컨트롤을 Toolbox에 등록 시 오류 [2]
10969정성태5/18/201624138.NET Framework: 586. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록파일 다운로드1
10968정성태5/18/201619124오류 유형: 332. Visual Studio - 단위 테스트 생성 시 "Design time expression evaluation" 오류 메시지
10967정성태5/12/201624289.NET Framework: 585. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
10966정성태5/12/201631918.NET Framework: 584. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본 [1]파일 다운로드1
10965정성태5/12/201623945디버깅 기술: 81. try/catch로 조용히 사라진 예외를 파악하고 싶다면?
10964정성태5/12/201622507오류 유형: 331. ASP.NET에서 System.BadImageFormatException 예외가 발생하는 경우
10963정성태5/11/201624745VS.NET IDE: 107. Visual Studio 2015의 "DTAR_..." 특수 폴더가 생성되는 문제파일 다운로드2
10962정성태5/11/201624927오류 유형: 330. Visual Studio 단위 테스트 시 DisconnectedContext 예외 발생
10961정성태5/11/201624722.NET Framework: 583. 문제 재현 - Managed Debugging Assistant 'DisconnectedContext' has detected a problem in '...'파일 다운로드1
10960정성태5/10/201622097오류 유형: 329. ATL 메서드 추가 마법사 창에서 8ce0000b 오류 발생
10959정성태5/9/201624777.NET Framework: 582. CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경파일 다운로드1
10958정성태5/6/201651777개발 환경 구성: 284. "Let's Encrypt"에서 제공하는 무료 SSL 인증서를 IIS에 적용하는 방법 (1) [3]
10957정성태5/3/201627050오류 유형: 328. 윈도우 백업 시 오류 - 0x80780166 두 번째 이야기 [1]
10956정성태5/3/201622514Windows: 117. BitLocker - This device can't use a Trusted Platform Module.
10955정성태5/3/201629212.NET Framework: 581. C# - 순열(Permutation) 예제 코드파일 다운로드2
10954정성태5/3/201630154.NET Framework: 580. C# - 조합(Combination) 예제 코드 [2]파일 다운로드1
10953정성태5/2/201619765.NET Framework: 579. Assembly.LoadFrom으로 로드된 어셈블리의 JIT 컴파일 코드 공유?파일 다운로드1
10952정성태5/2/201621844.NET Framework: 578. 도메인 중립적인 어셈블리가 비-도메인 중립적인 어셈블리를 참조하는 경우파일 다운로드1
10951정성태5/2/201619761.NET Framework: 577. CLR Profiler로 살펴보는 SharedDomain의 모듈 로드 동작파일 다운로드1
10950정성태5/2/201626231.NET Framework: 576. 기본적인 CLR Profiler 소스 코드 설명 [2]파일 다운로드2
10949정성태4/28/201619790.NET Framework: 575. SharedDomain과 JIT 컴파일파일 다운로드1
10948정성태4/28/201623699.NET Framework: 574. .NET - 눈으로 확인하는 SharedDomain의 동작 방식 [3]파일 다운로드1
10947정성태4/27/201621577.NET Framework: 573. .NET CLR4 보안 모델 - 4. CLR4 보안 모델에서의 조건부 APTCA 역할파일 다운로드1
10946정성태4/26/201624426VS.NET IDE: 106. Visual Studio 2015 확장 - INI 파일을 위한 사용자 정의 포맷 기능 (Syntax Highlighting)파일 다운로드1
... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...