를 찾는 기본 응용 프로그램을 위한 열기는 특정 파일 형식 Windows

StackOverflow https://stackoverflow.com/questions/162331

  •  03-07-2019
  •  | 
  •  

문제

나는 응용 프로그램을 개발하는 표적으로 하고 있다.NET Framework2.0 를 사용하여 C#을 위해 내가 필요할 수 있을 찾기 위해 기본 응용 프로그램를 위해 사용되는 열기는 특정 파일 형식입니다.

내가 알고 있는 경우,예를 들어,당신은 원하는 파일을 열고 파일을 사용하는 응용 프로그램 같은 것을 사용할 수 있습니다:

System.Diagnostics.Process.Start( "C:\...\...\myfile.html" );

를 HTML 문서를 열고 기본 브라우저에서,또는

System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" );

텍스트 파일을 열에 기본 텍스트 편집기입니다.

그러나 내가 원하는 무엇을 할 수 있는 파일을 열지 않는 반드시 .txt 확장자(예를 들어),기본 텍스트 편집기,그래서 내가 필요할 수 있을 찾아 기본 응용 프로그램을 위한 개방 .txt 파일을 수있는,나를 호출됩니다.

나는 추측이 있 Win32API 는 나는 필요 P/Invoke 이렇게하기 위해서는,그러나 빠른 모습을 가진 구글과 MSDN 공개하지 않았 아무것도의 많은 관심;내가 찾았어요 매우 많은 수의 완전하게 관련이 없는 페이지는,하지만 아무것도 같은 내가 찾고 있습니다.

도움이 되었습니까?

해결책

레지스트리 섹션에서 확인할 수 있습니다 HKEY_CLASSES_ROOT 확장 및 조치 세부 사항. 이것에 대한 문서입니다 MSDN에서. 또는 사용할 수 있습니다 iQueryAssociations 상호 작용.

다른 팁

모든 현재 답변은 신뢰할 수 없습니다. 레지스트리는 구현 세부 사항이며 실제로 이러한 코드는 내 Windows 8.1 컴퓨터에서 끊어집니다. 이를 수행하는 올바른 방법은 Win32 API를 사용하는 것입니다. ASSOCQUERYSTRING:

using System.Runtime.InteropServices;

[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern uint AssocQueryString(
    AssocF flags, 
    AssocStr str,  
    string pszAssoc, 
    string pszExtra, 
    [Out] StringBuilder pszOut, 
    ref uint pcchOut
); 

[Flags]
public enum AssocF
{
    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_Fixed_ProgId = 0x800,
    Is_Protocol = 0x1000,
    Init_For_File = 0x2000
}

public enum AssocStr
{
    Command = 1,
    Executable,
    FriendlyDocName,
    FriendlyAppName,
    NoOpen,
    ShellNewValue,
    DDECommand,
    DDEIfExec,
    DDEApplication,
    DDETopic,
    InfoTip,
    QuickTip,
    TileInfo,
    ContentType,
    DefaultIcon,
    ShellExtension,
    DropTarget,
    DelegateExecute,
    Supported_Uri_Protocols,
    ProgID,
    AppID,
    AppPublisher,
    AppIconReference,
    Max
}

관련 문서 :

샘플 사용 :

static string AssocQueryString(AssocStr association, string extension)
{
    const int S_OK = 0;
    const int S_FALSE = 1;

    uint length = 0;
    uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length);
    if (ret != S_FALSE)
    {
        throw new InvalidOperationException("Could not determine associated string");
    }

    var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination
    ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length);
    if (ret != S_OK)
    {
        throw new InvalidOperationException("Could not determine associated string"); 
    }

    return sb.ToString();
}

도! 물론.

HKEY_CLASSES_ROOT\.txt

에 대한 참조가 포함되어 있습니다

HKEY_CLASSES_ROOT\txtfile

서브 키가 포함되어 있습니다

HKEY_CLASSES_ROOT\txtfile\shell\open\command

메모장을 참조하십시오.

정렬, 많은 감사합니다!

바트

다음은이 주제에 대한 블로그 게시물입니다. 코드 샘플은 vb.net에 있지만 C#으로 쉽게 포트 할 수 있어야합니다.

할 수 있습 쿼리 레지스트리입니다.첫째는 기본 입장에서 HKEY_CLASSES_ROOT\.ext

제공 할 것입니다 classname.예를 들어.txt 는 기본값 txtfile 를 갖

다음을 열어 HKEY_CLASSES_ROOT xtfile 를 갖\Shell\Open\명령

는 기본 명령을 사용합니다.

늦은 답변이지만 파일 연관성을 처리하는 좋은 Nuget 패키지가 있습니다 : 파일 협회

링크 너겟 파일 협회

예를 들어 허용되는 모든 파일 확장자를 컨텍스트 메뉴에 추가하는 것과 같은 사용법은 간단합니다.

private void OnMenuSourceFileOpening(object sender, ...)
{   // open a context menu with the associated files + ".txt" files
    if (File.Exists(this.SelectedFileName))
    {
        string fileExt = Path.GetExtension(this.SelectedFileNames);
        string[] allowedExtensions = new string[] { fileExt, ".txt" };
        var fileAssociations = allowedExtensions
            .Select(ext => new FileAssociationInfo(ext));
        var progInfos = fileAssociations
            .Select(fileAssoc => new ProgramAssociationInfo (fileAssoc.ProgID));
        var toolstripItems = myProgInfos
            .Select(proginfo => new ToolStripLabel (proginfo.Description) { Tag = proginfo });
        // add also the prog info as Tag, for easy access
        //  when the toolstrip item is selected
        // of course this can also be done in one long linq statement

        // fill the context menu:
        this.contextMenu1.Items.Clear();
        this.contextMenuOpenSourceFile.Items.AddRange (toolstripItems.ToArray());
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top