gpt4 book ai didi

c# - 在 Windows 上查找用于打开特定文件类型的默认应用程序

转载 作者:IT王子 更新时间:2023-10-29 03:48:53 24 4
gpt4 key购买 nike

我正在使用 C# 开发面向 .NET Framework 2.0 的应用程序,为此我需要能够找到用于打开特定文件类型的默认应用程序。

我知道,例如,如果您只想使用该应用程序打开一个文件,您可以使用类似的东西:

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

在默认浏览器中打开 HTML 文档,或者

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

在默认文本编辑器中打开文本文件。

但是,我希望能够在默认文本编辑器中打开不一定具有 .txt 扩展名(例如)的文件,因此我需要能够找到打开 .txt 文件的默认应用程序,这将允许我直接调用它。

我猜我需要 P/Invoke 一些 Win32 API 才能执行此操作,但是快速浏览 Google 和 MSDN 并没有发现任何有趣的东西;我确实找到了大量完全不相关的页面,但没有像我正在寻找的那样。

最佳答案

目前所有的答案都是不可靠的。注册表是一个实现细节,实际上这样的代码在我的 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();
}

关于c# - 在 Windows 上查找用于打开特定文件类型的默认应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/162331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com