前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >如何将应用程序与文件类型(文件扩展名)关联起来

如何将应用程序与文件类型(文件扩展名)关联起来

作者头像
jgrass
发布2024-12-25 16:15:54
发布2024-12-25 16:15:54
5700
代码可运行
举报
文章被收录于专栏:蔻丁杂记蔻丁杂记
运行总次数:0
代码可运行

自定义一个文件格式,如 .jgrass ,如何将这种文件格式与对应的程序关联起来? 或者,自己编写了一个可以打开 txt 格式的应用程序,怎么能够通过双击 txt 文件,直接打开这个自定义程序?

基本思路是向注册表中写入或修改一些值。

具体可以参见:

如何为你的 Windows 应用程序关联一种或多种文件类型 - walterlv

注册表中的文件扩展名

注册表中的关联程序

举个栗子

e.g. 怎么修改 txt 文件的默认打开格式?

理论上讲,有两种实现方式。

1 修改上图 1 中的 .txt 项的默认值,将其修改为自定义的程序ID,然后在注册表中添加自定义的程序ID,已经其对应的执行程序的路径。

2 修改 txtfile 项中的默认值,直接将其路径修改为自定义程序的路径。

看起来 2 的修改更小,更省事。但这是有问题的。

因为 txtfile 可能不止关联了 .txt 这一种文件格式,还关联了很多其他的格式,直接修改 txtfile 中的值,可能会导致这些文件打不开。

txtfile 这个注册表项,除了程序 NOTEPAD.EXE 的发布者可以修改之外,其他应用都不应该去修改它,此项是对修改封闭的。

而采用方式 1,只会影响 .txt 这一种文件格式的打开方式。在注册表中添加自定义的程序ID,这是一种扩展开放的修改方式。

具体代码

下面是具体代码。

nuget 引用 (来源:nuget.org)

<PackageReference Include="Walterlv.Win32.Source" Version="0.12.2-alpha"/>

向注册表中注册可执行程序

代码语言:javascript
代码运行次数:0
复制
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Microsoft.Win32;using Walterlv.Win32;
namespace GrassDemoPark.WPF2.Tiny.RegEdit{    /*     * [如何为你的 Windows 应用程序关联一种或多种文件类型 - walterlv]     * (https://blog.walterlv.com/post/windows-file-type-association.html)     */
    /// <summary>    /// 向注册表中注册可执行程序    /// </summary>    class RegisterProgram    {        /// <summary>        /// 需要管理的执行程序的产品ID,(厂商名.应用名.版本号)        /// e.g. Microsoft.PowerShellConsole.1        /// </summary>        public string ProgramId { get; }
        /// <summary>        /// 该执行程序所关联文件的类型描述        /// e.g. Text Document        /// </summary>        public string? TypeName { get; set; }
        /// <summary>        /// 该执行程序所关联文件的类型描述        /// e.g. 一个神奇的文本文件        /// </summary>        public string? FriendlyTypeName { get; set; }
        /// <summary>        /// 该执行程序所关联文件对应的 Icon        /// </summary>        public string? DefaultIcon { get; set; }
        /// <summary>        /// 是否总是显示指定文件类型的扩展名        /// </summary>        public bool? IsAlwaysShowExt { get; set; }
        /// <summary>        /// 该执行程序可执行的操作/谓词        /// </summary>        public string? Operation { get; set; }
        /// <summary>        /// 对应谓词下,其执行的具体命令;仅在<see cref="Operation"/>有效时,此值才有效        /// </summary>        public string? Command { get; set; }
        /// <summary>        /// 根据指定 ProgramId,创建 <see cref="RegisterProgram"/> 的实例。        /// </summary>        /// <param name="programId"></param>        public RegisterProgram(string programId)        {            if (string.IsNullOrWhiteSpace(programId))            {                throw new ArgumentNullException(nameof(programId));            }
            ProgramId = programId;        }
        /// <summary>        /// 将此文件扩展名注册到当前用户的注册表中        /// </summary>        public void WriteToCurrentUser()        {            WriteToRegistry(RegistryHive.CurrentUser);        }
        /// <summary>        /// 将此文件扩展名注册到所有用户的注册表中。(进程需要以管理员身份运行)        /// </summary>        public void WriteToAllUser()        {            WriteToRegistry(RegistryHive.LocalMachine);        }
        /// <summary>        /// 将此文件扩展名写入到注册表中        /// </summary>        private void WriteToRegistry(RegistryHive registryHive)        {            // 写 默认描述            registryHive.Write32(BuildRegistryPath(ProgramId), TypeName ?? string.Empty);
            // 写 FriendlyTypeName            if (FriendlyTypeName != null && !string.IsNullOrWhiteSpace(FriendlyTypeName))            {                registryHive.Write32(BuildRegistryPath(ProgramId), "FriendlyTypeName", FriendlyTypeName);            }
            // 写 IsAlwaysShowExt            if (IsAlwaysShowExt != null)            {                registryHive.Write32(BuildRegistryPath(ProgramId), "IsAlwaysShowExt", IsAlwaysShowExt.Value ? "1" : "0");            }
            // 写 Icon            if (DefaultIcon != null && !string.IsNullOrWhiteSpace(DefaultIcon))            {                registryHive.Write32(BuildRegistryPath($"{ProgramId}\\DefaultIcon"), DefaultIcon);            }
            // 写 Command            if (Operation != null && !string.IsNullOrWhiteSpace(Operation))            {                registryHive.Write32(BuildRegistryPath($"{ProgramId}\\shell\\{Operation}\\command"), Command ?? string.Empty);            }        }
        private string BuildRegistryPath(string relativePath)        {            return $"Software\\Classes\\{relativePath}";        }    }}

向注册表中注册文件扩展名

代码语言:javascript
代码运行次数:0
复制
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Microsoft.Win32;using Walterlv.Win32;
namespace GrassDemoPark.WPF2.Tiny.RegEdit{    /*     * [如何为你的 Windows 应用程序关联一种或多种文件类型 - walterlv]     * (https://blog.walterlv.com/post/windows-file-type-association.html)     */
    /// <summary>    /// 向注册表中注册文件扩展名    /// </summary>    class RegisterFileExtension    {        /// <summary>        /// 文件后缀名(带.)        /// </summary>        public string FileExtension { get; }
        /// <summary>        /// 该后缀名所指示的文件的类型        /// e.g. text/plain        /// [MIME 类型 - HTTP | MDN](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types )        /// [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml )        /// </summary>        public string? ContentType { get; set; }
        /// <summary>        /// 该后缀名所指示的文件的感知类型        /// e.g. text        /// [Perceived Types (Windows) | Microsoft Docs](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/cc144150(v%3Dvs.85) )        /// </summary>        public string? PerceivedType { get; set; }
        /// <summary>        /// 该后缀名所指示的文件关联的默认应用程序的 ProgramId        /// </summary>        public string? DefaultProgramId { get; set; }
        /// <summary>        /// 该后缀名所指示的文件,还可以被哪些 ProgramId 所代表的程序打开。        /// </summary>        public IList<string> OpenWithProgramIds { get; set; } = new List<string>();
        /// <summary>        /// 根据指定文件扩展名,创建 <see cref="RegisterFileExtension"/> 的实例。        /// </summary>        /// <param name="fileExtension"></param>        public RegisterFileExtension(string fileExtension)        {            if (string.IsNullOrWhiteSpace(fileExtension))            {                throw new ArgumentNullException(nameof(fileExtension));            }
            if (!fileExtension.StartsWith(".", StringComparison.Ordinal))            {                throw new ArgumentException(                    $"{fileExtension} is not a valid file extension. it must start with \".\"",                    nameof(fileExtension));            }            FileExtension = fileExtension;        }
        /// <summary>        /// 将此文件扩展名注册到当前用户的注册表中        /// </summary>        public void WriteToCurrentUser()        {            WriteToRegistry(RegistryHive.CurrentUser);        }
        /// <summary>        /// 将此文件扩展名注册到所有用户的注册表中。(进程需要以管理员身份运行)        /// </summary>        public void WriteToAllUser()        {            WriteToRegistry(RegistryHive.LocalMachine);        }
        /// <summary>        /// 将此文件扩展名写入到注册表中        /// </summary>        private void WriteToRegistry(RegistryHive registryHive)        {            // 写默认执行程序            registryHive.Write32(BuildRegistryPath(FileExtension), DefaultProgramId ?? string.Empty);
            // 写 ContentType            if (ContentType != null && !string.IsNullOrWhiteSpace(ContentType))            {                registryHive.Write32(BuildRegistryPath(FileExtension), "Content Type", ContentType);            }
            // 写 PerceivedType            if (PerceivedType != null && !string.IsNullOrWhiteSpace(PerceivedType))            {                registryHive.Write32(BuildRegistryPath(FileExtension), "PerceivedType", PerceivedType);            }
            // 写 OpenWithProgramIds            if (OpenWithProgramIds.Count > 0)            {                foreach (string programId in OpenWithProgramIds)                {                    registryHive.Write32(BuildRegistryPath($"{FileExtension}\\OpenWithProgids"), programId, string.Empty);                }            }        }
        private string BuildRegistryPath(string relativePath)        {            return $"Software\\Classes\\{relativePath}";        }
    }}

原文链接: https://cloud.tencent.com/developer/article/2481463

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年12月1日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 注册表中的文件扩展名
  • 注册表中的关联程序
  • 举个栗子
  • 具体代码
    • 向注册表中注册可执行程序
    • 向注册表中注册文件扩展名
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档