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분
정성태

... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12317정성태9/9/202011240개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/20209671디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
12315정성태9/7/202011925개발 환경 구성: 510. Logstash - FileBeat을 이용한 IIS 로그 처리 [2]
12314정성태9/7/202010326오류 유형: 645. IIS HTTPERR - Timer_MinBytesPerSecond, Timer_ConnectionIdle 로그
12313정성태9/6/202011648개발 환경 구성: 509. Logstash - 사용자 정의 grok 패턴 추가를 이용한 IIS 로그 처리
12312정성태9/5/202015658개발 환경 구성: 508. Logstash 기본 사용법 [2]
12311정성태9/4/202010803.NET Framework: 937. C# - 간단하게 만들어 보는 리눅스의 nc(netcat), json_pp 프로그램 [1]
12310정성태9/3/202010040오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/20209754개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011054개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202011830오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/20209945오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202010896Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/20209844개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010000개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/20209980.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202010231오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/20209686.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202010612.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
12298정성태8/27/202010296오류 유형: 640. livekd - Could not resolve symbols for ntoskrnl.exe: MmPfnDatabase
12297정성태8/25/20209492개발 환경 구성: 503. SHA256 테스트 인증서 생성 방법
12296정성태8/24/202010000.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger파일 다운로드1
12295정성태8/24/20209346오류 유형: 639. Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket ,,,
12293정성태8/24/202010686Windows: 171. "Administered port exclusions" 설명
12292정성태8/20/202011936.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202010886오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...