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]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13601정성태4/19/2024214닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024283닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024321닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024350닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024424닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024794닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024914닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241018닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241049개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241588개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241138닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241876닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...