更改 .txt 的默认应用程序

Change default application for .txt

在互联网上搜索了很多都没有成功,我在这里寻求帮助。

这个问题看起来很简单,但不幸的是我无法解决它。

我想更改默认应用程序以打开 .txt 文件。例如,我不想使用记事本,而是使用位于 C:\Program Files\Windows NT\Accessories\wordpad.exe

的写字板

所以我尝试更改注册表:HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\OpenWithProgids 但没有成功。

我还找到了一个尝试更改组策略的解决方案。此代码如下所示:

string tempFile = Path.GetTempFileName();
string xmlFile = tempFile.Replace(".tmp", ".xml");
File.Move(tempFile, xmlFile);

XDocument document = new XDocument(new XElement("DefaultAssociations",
    new XElement("Association",
        new XAttribute("Identifier", ".txt"),
        new XAttribute("ProgId", "txtFile"),
        new XAttribute("ApplicationName", "Editor"))));
document.Save(xmlFile);

ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\Software\Policies\Microsoft\Windows\System!DefaultAssociationsConfiguration",
    xmlFile, RegistryValueKind.String);

但这也行不通。

我也尝试过使用命令行 ftype,但也没有用。

谁能告诉我如何更改给定文件类型的关联应用程序?

我猜你想这样做是因为你的程序中有某种 Set as default 选项,顺便说一下,我花了最后一个小时试图弄清楚为什么它不起作用,在这里到目前为止我发现了什么。

您需要执行的步骤如下:

  • 在 ClassesRoot 中为 .custom 扩展创建一个注册表项。 (时期很重要)

代码:

Registry.ClassesRoot.CreateSubKey(".custom").SetValue("", "customfile", Microsoft.Win32.RegistryValueKind.String);`
  • 正在创建“Customfile”子项和“customfile\open\command” 存储应用程序路径所需的子项 打开此文件类型。

代码:

Registry.ClassesRoot.CreateSubKey("Customfile\shell\open\command").SetValue("", PATH_TO_YOUR_EXE, Microsoft.Win32.RegistryValueKind.String);

现在关联已经建立,您的应用程序将注册成为可以打开该扩展程序的应用程序之一。


.txt(或其他已经关联的扩展名)的情况

稍微弄乱之后,我发现要对已经关联的扩展进行更改,您还需要编辑注册表

示例(带有 .txt 扩展名)

 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\UserChoice

此键有一个 ProgId 值,该值实际上包含 用户设置的默认应用程序 ,该值为 string。所以你也将做 edit/delete 这个注册表。

希望对您有所帮助:)!