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)
13558정성태2/18/20242152닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241904Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241949Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242103닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241851VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241935닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241883닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242079닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242164Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242494개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242321개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242069개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241924Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241845닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241856오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241852Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241886오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241932VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242060Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242339개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242402닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242461닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242565닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242406닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242240닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242452닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...