首页 > 后端开发 > C++ > 如何以编程方式查找 .NET 中文件类型的默认应用程序?

如何以编程方式查找 .NET 中文件类型的默认应用程序?

Linda Hamilton
发布: 2025-01-04 10:08:39
原创
541 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板