Microsoft MVP성태의 닷넷 이야기
.NET Framework: 675. C# - (파일) 확장자와 연결된 실행 파일 경로 찾기 [링크 복사], [링크+제목 복사],
조회: 16548
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - (파일) 확장자와 연결된 실행 파일 경로 찾기

다음과 같은 질문이 있군요.

파일 확장자명을 이용해 파일의 실행 프로그램의 전체 경로를 얻어 올 수 있을까요?
; https://www.sysnet.pe.kr/3/0/4874

질문에서 언급한 ProgramAssociationInfo 타입은 닷넷 기본 BCL에 포함된 것은 아닙니다. 그렇다면 누군가 만들었다는 것인데 BCL에는 없으니까 만들었겠죠? ^^

암튼, File Association과 관련한 모든 정보는 레지스트리에 있습니다. 따라서 이런 경우 Win32 API의 힘을 빌릴 수 있습니다. 검색해 보면, 이에 대해 FindExecutable이 있다고 합니다.

Is an Application Associated With a Given Extension?
; https://stackoverflow.com/questions/9540051/is-an-application-associated-with-a-given-extension

C#으로는 다음과 같이 코딩할 수 있습니다.

[DllImport("shell32.dll")]
public static extern int FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult);

FileAssociation.FindExecutable(@"C:\temp\test.txt", string.Empty, sb);

근데, 문제는 실제 파일이 있어야만 동작하기 때문에 확장자만으로 찾을 수 없습니다. 게다가 일부 파일에 대해서만 가능한데... 기준을 잘 모르겠습니다. 가령 c:\temp 폴더에 있는 test.cs 파일을 지정했는데 이에 대해서는 비주얼 스튜디오에 대한 경로가 아닌 빈 문자열을 반환합니다.

자... 그럼 그다음으로 생각할 수 있는 것이 바로 AssocQueryString win32 API입니다. 사용법은 다음과 같이 마련해 주고,

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace ConsoleApp1
{
    class FileAssociation
    {
        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static unsafe extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut);

        [DllImport("shell32.dll")]
        public static extern int FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult);

        public unsafe static void ListAssociationInfo(string extension)
        {
            StringBuilder sb = new StringBuilder(1024);

            foreach (string name in Enum.GetNames(typeof(AssocStr)))
            {
                uint cchOut = 1024 / 2;

                AssocStr value = (AssocStr)Enum.Parse(typeof(AssocStr), name);
                uint result = AssocQueryString(AssocF.None, value, extension, null, sb, ref cchOut);

                Console.Write(name + " == ");

                if (result == 0)
                {
                    Console.Write(sb.ToString());
                } // 0x80070483 == No application is associated with the specified file for this operation. 

                Console.WriteLine();
            }
        }
    }

    [Flags]
    enum AssocF : uint
    {
        None = 0,
        Init_NoRemapCLSID = 0x1,
        Init_ByExeName = 0x2,
        Open_ByExeName = 0x2,
        Init_DefaultToStar = 0x4,
        Init_DefaultToFolder = 0x8,
        NoUserSettings = 0x10,
        NoTruncate = 0x20,
        Verify = 0x40,
        RemapRunDll = 0x80,
        NoFixUps = 0x100,
        IgnoreBaseClass = 0x200,
        Init_IgnoreUnknown = 0x400,
        Init_FixedProgId = 0x800,
        IsProtocol = 0x1000,
        InitForFile = 0x2000,
    }

    enum AssocStr
    {
        Command = 1,
        Executable,
        FriendlyDocName,
        FriendlyAppName,
        NoOpen,
        ShellNewValue,
        DDECommand,
        DDEIfExec,
        DDEApplication,
        DDETopic,
        InfoTip,
        QuickTip,
        TileInfo,
        ContentType,
        DefaultIcon,
        ShellExtension,
        DropTarget,
        DelegateExecute,
        SupportedUriProtocols,
        Max,
    }
}

이렇게 호출하면,

FileAssociation.ListAssociationInfo(@".pdf");

다음과 같은 정보를 얻을 수 있습니다.

Command == "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "%1"
Executable == C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe
FriendlyDocName == Adobe Acrobat Document
FriendlyAppName == Adobe Acrobat Reader DC
NoOpen ==
ShellNewValue ==
DDECommand ==
DDEIfExec ==
DDEApplication == AcroRd32
DDETopic == System
InfoTip == prop:System.ItemTypeText;System.Size;System.DateModified
QuickTip == prop:System.ItemTypeText;System.Size;System.DateModified
TileInfo == prop:System.ItemTypeText;System.Size;System.DateModified
ContentType == application/pdf
DefaultIcon == C:\Windows\Installer\{AC76BA86-7AD7-1042-7B44-AC0F074E4100}\PDFFile_8.ico,0
ShellExtension ==
DropTarget ==
DelegateExecute ==
SupportedUriProtocols == file:
Max == AcroExch.Document.DC

대충 Executable이 맞을 것 같은데요. 반면 ".cs" 확장자로 해보니 다음과 같은 결과가 나옵니다.

Command == "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" /dde
Executable ==
FriendlyDocName == Visual C# Source file
FriendlyAppName ==
NoOpen ==
ShellNewValue ==
DDECommand == Open("%1")
DDEIfExec ==
DDEApplication == VisualStudio.14.0
DDETopic == system
InfoTip == prop:System.ItemTypeText;System.Size;System.DateModified
QuickTip == prop:System.ItemTypeText;System.Size;System.DateModified
TileInfo == prop:System.ItemTypeText;System.Size;System.DateModified
ContentType == text/plain
DefaultIcon == C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC#\VCSPackages\csproj.dll,1
ShellExtension ==
DropTarget ==
DelegateExecute ==
SupportedUriProtocols == file:
Max == VisualStudio.cs.14.0

따라서 확률을 좀 더 높이려면 Command의 문자열을 가져와 exe 경로만을 분리해서 구하는 것이 더 좋을 것 같습니다.

하나 더 테스트해볼까요? ^^ ".mp3"로 했더니 이런 결과가 나옵니다.

Command ==
Executable ==
FriendlyDocName == MP3 File
FriendlyAppName == Groove 음악
NoOpen ==
ShellNewValue ==
DDECommand ==
DDEIfExec ==
DDEApplication ==
DDETopic == System
InfoTip == prop:System.ItemType;System.Size;System.Music.Artist;System.Media.Duration;System.OfflineAvailability
QuickTip == prop:System.ItemTypeText;System.Size;System.DateModified
TileInfo == prop:System.ItemTypeText;System.Size;System.DateModified
ContentType == audio/mpeg
DefaultIcon == @{Microsoft.ZuneMusic_10.17062.14111.0_x64__8wekyb3d8bbwe?ms-resource://Microsoft.ZuneMusic/Files/Assets/FileExtension.png}
ShellExtension ==
DropTarget ==
DelegateExecute == {4ED3A719-CEA8-4BD9-910D-E252F997AFC2}
SupportedUriProtocols == *:
Max == AppXqj98qxeaynz6dv4459ayz6bnqxbyaqcs

Command와 Executable이 아예 비어 있습니다. 대신 눈에 띄는 것이 있다면 DelegateExecute인데요, 해당 GUID 값으로 레지스트리를 검색해 보니 다음의 정보가 나옵니다.

[HKEY_CLASSES_ROOT\CLSID\{4ED3A719-CEA8-4BD9-910D-E252F997AFC2}]
@="Association Launch Execute Command"

[HKEY_CLASSES_ROOT\CLSID\{4ED3A719-CEA8-4BD9-910D-E252F997AFC2}\InProcServer32]
@="%SystemRoot%\system32\twinui.dll"
"ThreadingModel"="Apartment"

[HKEY_CLASSES_ROOT\CLSID\{4ED3A719-CEA8-4BD9-910D-E252F997AFC2}\SupportedProtocols]
@="*"

"Association Launch Execute Command"라는데, 재미있는 것은 제 컴퓨터에는 .mp3를 실행하면 Windows Store 앱 중에서 Groove 음악 플레이어가 뜬다는 점입니다. 아마도 Store App으로 연결된 확장자들은 "4ED3A719-CEA8-4BD9-910D-E252F997AFC2" 핸들러가 중계 처리해 주는 것이 아닌가 싶습니다. 실제로 레지스트리의 "HKEY_CLASSES_ROOT\.mp3" 항목을 봐도 실행 파일에 대한 정보는 찾을 수 없었습니다.

이런 식으로 못 가져오는 경우가 종종 있습니다. 가령 .sln 파일의 경우 Visual Studio는 다중 버전을 고려한 Visual Studio Version Selector로 연결되어 있고 그 프로그램이 .sln 파일의 내용에 따라 어느 버전의 비주얼 스튜디오인지 판단해서 그 버전의 devenv.exe를 실행합니다. 따라서, 특정 확장자로 바로 연결된 EXE를 찾는 것은 쉽지 않은 일입니다.

그래도 이 정도면, 특수한 경우를 제외하고는 제법 방법이 나온 것 같군요. ^^

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/21/2023]

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

비밀번호

댓글 작성자
 



2017-08-24 12시59분
[ho] 이렇게 내용을 정리해 주시니 많은 도움이 될 것 같습니다.
언급해 주신 부분 처럼 특수한 경우를 제외한다면 정리해 주신 부분을 활용해
외부 프로그램을 실행시키고 완료 시점을 확인 할 수 있을 것 같습니다.
특수한 경우(배치파일, Store App, 외부 프로그램에서 호출된 외부프로그램..)를
예외 처리한 형태로 진행을 해야겠네요

감사합니다!
[guest]
2019-05-30 09시40분
[지나가는 사람] 정말 좋은 정보 공유에 감사드립니다.
[guest]

... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11815정성태2/14/201911305오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910118오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911704.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199573오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913330오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911387.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912890.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201913967디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912278Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201912011디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913880.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201911915Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911405디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912784.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913809개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813098오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813917.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813143개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201810514개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810167개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201812553Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/20189947오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201811569개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201812333Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201812324VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201810656오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...