首頁 >後端開發 >C++ >如何以程式設計方式尋找 .NET 中文件類型的預設應用程式?

如何以程式設計方式尋找 .NET 中文件類型的預設應用程式?

Linda Hamilton
Linda Hamilton原創
2025-01-04 10:08:39568瀏覽

How Can I Programmatically Find the Default Application for a File Type in .NET?

尋找在Windows (.NET) 上開啟檔案類型的預設應用程式

在使用C# 的.NET Framework 2.0 中,可以使用System.Diagnostics.Process.Start() 在預設應用程式中開啟檔案。但是,對於沒有特定擴展名的文件,確定關聯的應用程式可能會很棘手。

使用 Win32 API

要克服此限制,請利用 Win32 API 函數 AssocQueryString( )推薦。此函數傳回與特定檔案類型關聯的字串,允許開發人員提取預設應用程式的可執行路徑。

下面的程式碼片段示範如何使用AssocQueryString():

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

public static string GetDefaultApplicationForExtension(string extension)
{
    const int S_OK = 0;
    const int S_FALSE = 1;

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

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

    return sb.ToString();
}

透過呼叫此函數並提供檔案副檔名作為參數,開發人員可以獲得預設的應用程式路徑,使他們能夠以程式設計方式開啟所需應用程式中的檔案。

以上是如何以程式設計方式尋找 .NET 中文件類型的預設應用程式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn