Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (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]

... 31  32  33  [34]  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12772정성태8/11/20219343스크립트: 21. 파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 uwsgi를 이용해 실행 [1]
12771정성태8/11/20217728Windows: 196. "Microsoft Windows Subsystem for Linux Background Host" / "Vmmem"을 종료하는 방법
12770정성태8/11/20218429.NET Framework: 1086. C# - Windows Forms 응용 프로그램의 자식 컨트롤 부하파일 다운로드1
12769정성태8/11/20216413오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main 두 번째 이야기
12768정성태8/10/20217436.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [1]파일 다운로드1
12767정성태8/10/20218495오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main
12766정성태8/9/20217023Java: 32. closing inbound before receiving peer's close_notify
12765정성태8/9/20216338Java: 31. Cannot load JDBC driver class 'org.mysql.jdbc.Driver'
12764정성태8/9/202144801Java: 30. XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid
12763정성태8/9/20217822Java: 29. java.lang.NullPointerException - com.mysql.jdbc.ConnectionImpl.getServerCharset
12762정성태8/8/202111337Java: 28. IntelliJ - Unable to open debugger port 오류
12761정성태8/8/20218555Java: 27. IntelliJ - java: package javax.inject does not exist [2]
12760정성태8/8/20215969개발 환경 구성: 594. 전용 "Command Prompt for ..." 단축 아이콘 만들기
12759정성태8/8/20219089Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [2]파일 다운로드1
12758정성태8/7/20218430오류 유형: 751. Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
12757정성태8/7/20219116Java: 25. IntelliJ + Spring Framework 프로젝트 생성
12756정성태8/6/20217932.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법 [1]파일 다운로드1
12755정성태8/5/20217062개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법파일 다운로드1
12754정성태8/5/20217999오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218216오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216317개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/20219360개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216178디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20215595개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216207개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20216798오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
... 31  32  33  [34]  35  36  37  38  39  40  41  42  43  44  45  ...