How will the application file type (file extension) associates?

A custom file format, such as .jgrass, how to associate with this file format corresponding to the program?
Or, I have written a can open txtthe application format, how can double-click txtthe file, directly open the custom program?

The basic idea is to write or modify some of the values to the registry.
Specific can be found in:

How to link one or more file types for your Windows applications - walterlv

Registry file extensions

Associated program registry

For chestnuts

eg how to modify txtthe default file format to open?

In theory, there are two implementations.
1 in FIG. 1 modified .txtdefault value of the item, change it to a custom program ID, program ID and add custom in the registry, the path of execution of the program has its corresponding.
2 Modify txtfileDefault entry, directly modify its path custom path.

Amendment 2 looks smaller, easier way. But this is problematic.
Because the txtfilepossible association of more than .txtthis kind of file format, also associated with many other formats, directly modify the txtfilevalues, could lead to open these files.
txtfileThis registry key, in addition to programs NOTEPAD.EXEother than the publisher can be modified, other applications should not be to modify it, this is a modification closed.

The use of 1, affects only .txtthis kind of file format Open. Add a custom program ID in the registry, which is an open extension modifications.

Specific code

The following is a specific code.

nuget references (Source: nuget.org)
<PackageReference Include="Walterlv.Win32.Source" Version="0.12.2-alpha"/>

Registration executable program to the registry

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}";
        }
    }
}

Extensions to the registry registration file

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}";
        }

    }
}

Original link:
https://www.cnblogs.com/jasongrass/p/11965647.html

Guess you like

Origin www.cnblogs.com/jasongrass/p/11965647.html