如何将文件扩展名与C#中的当前可执行文件关联

53 c# windows winforms

我想将文件扩展名与C#中的当前可执行文件相关联.这样,当用户在资源管理器中点击该文件后,它将以给定文件作为第一个参数运行我的可执行文件.理想情况下,它还会将给定文件扩展名的图标设置为我的可执行文件的图标.谢谢大家.

X-C*_*bed 40

似乎没有用于直接管理文件关联的.Net API,但您可以使用Registry类来读取和编写所需的密钥.

您需要在HKEY_CLASSES_ROOT下创建一个密钥,并将名称设置为您的文件扩展名(例如:".txt").将此键的默认值设置为文件类型的唯一名称,例如"Acme.TextFile".然后在HKEY_CLASSES_ROOT下创建另一个键,名称设置为"Acme.TextFile".添加一个名为"DefaultIcon"的子项,并将该键的默认值设置为包含您要用于此文件类型的图标的文件.添加另一个名为"shell"的兄弟.在"shell"键下,通过Explorer上下文菜单为您希望提供的每个操作添加一个键,将每个键的默认值设置为可执行文件的路径,后跟空格和"%1"以表示路径到选中的文件.

例如,这是一个示例注册表文件,用于在.txt文件和EmEditor之间创建关联:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.txt]
@="emeditor.txt"

[HKEY_CLASSES_ROOT\emeditor.txt]
@="Text Document"

[HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon]
@="%SystemRoot%\\SysWow64\\imageres.dll,-102"

[HKEY_CLASSES_ROOT\emeditor.txt\shell]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\open]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" \"%1\""

[HKEY_CLASSES_ROOT\emeditor.txt\shell\print]

[HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" /p \"%1\""


Ish*_*eel 25

此外,如果您决定采用注册表方式,请记住当前用户关联位于HKEY_CURRENT_USER\Software\Classes下.在那里添加应用程序而不是本地机器类可能更好.

如果您的程序将由受限用户运行,则无论如何都无法修改CLASSES_ROOT.


Mar*_*ell 12

如果您使用ClickOnce部署,这一切都是为您处理的(至少在VS2008 SP1中); 只是:

  • 项目属性
  • 发布
  • 选项
  • 文件关联
  • (添加你需要的任何东西)

(请注意,它必须是完全信任的,目标是.NET 3.5,并设置为脱机使用)

另请参见MSDN:如何:为ClickOnce应用程序创建文件关联


Kir*_*kov 9

这是一个完整的例子:

public class FileAssociation
{
    public string Extension { get; set; }
    public string ProgId { get; set; }
    public string FileTypeDescription { get; set; }
    public string ExecutableFilePath { get; set; }
}

public class FileAssociations
{
    // needed so that Explorer windows get refreshed after the registry is updated
    [System.Runtime.InteropServices.DllImport("Shell32.dll")]
    private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);

    private const int SHCNE_ASSOCCHANGED = 0x8000000;
    private const int SHCNF_FLUSH = 0x1000;

    public static void EnsureAssociationsSet()
    {
        var filePath = Process.GetCurrentProcess().MainModule.FileName;
        EnsureAssociationsSet(
            new FileAssociation
            {
                Extension = ".binlog",
                ProgId = "MSBuildBinaryLog",
                FileTypeDescription = "MSBuild Binary Log",
                ExecutableFilePath = filePath
            },
            new FileAssociation
            {
                Extension = ".buildlog",
                ProgId = "MSBuildStructuredLog",
                FileTypeDescription = "MSBuild Structured Log",
                ExecutableFilePath = filePath
            });
    }

    public static void EnsureAssociationsSet(params FileAssociation[] associations)
    {
        bool madeChanges = false;
        foreach (var association in associations)
        {
            madeChanges |= SetAssociation(
                association.Extension,
                association.ProgId,
                association.FileTypeDescription,
                association.ExecutableFilePath);
        }

        if (madeChanges)
        {
            SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
        }
    }

    public static bool SetAssociation(string extension, string progId, string fileTypeDescription, string applicationFilePath)
    {
        bool madeChanges = false;
        madeChanges |= SetKeyDefaultValue(@"Software\Classes\" + extension, progId);
        madeChanges |= SetKeyDefaultValue(@"Software\Classes\" + progId, fileTypeDescription);
        madeChanges |= SetKeyDefaultValue($@"Software\Classes\{progId}\shell\open\command", "\"" + applicationFilePath + "\" \"%1\"");
        return madeChanges;
    }

    private static bool SetKeyDefaultValue(string keyPath, string value)
    {
        using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
        {
            if (key.GetValue(null) as string != value)
            {
                key.SetValue(null, value);
                return true;
            }
        }

        return false;
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

您可能有特定原因选择不为项目使用安装包,但安装包是轻松执行应用程序配置任务的好地方,例如注册文件扩展名,添加桌面快捷方式等.

以下是使用内置Visual Studio Install工具创建文件扩展名关联的方法:

  1. 在现有的C#解决方案中,添加一个新项目并选择项目类型为Other Project Types- > Setup and Deployment- > Setup Project(或尝试安装向导)

  2. 配置安装程序(如果需要帮助,请提供大量现有文档)

  3. 右键单击解决方案资源管理器中的安装项目,选择View- > File Types,然后添加要注册的扩展以及运行它的程序.

如果用户为您的应用程序运行卸载,则此方法具有自行清理的额外好处.


Str*_*ong 5

要具体说明"Windows注册表"的方式:

我在HKEY_CURRENT_USER\Software\Classes下创建了密钥(就像Ishmaeel所说的那样)

并按照X-Cubed的说明进行操作.

示例代码如下所示:

private void Create_abc_FileAssociation()
{
    /***********************************/
    /**** Key1: Create ".abc" entry ****/
    /***********************************/
    Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

    key1.CreateSubKey("Classes");
    key1 = key1.OpenSubKey("Classes", true);

    key1.CreateSubKey(".abc");
    key1 = key1.OpenSubKey(".abc", true);
    key1.SetValue("", "DemoKeyValue"); // Set default key value

    key1.Close();

    /*******************************************************/
    /**** Key2: Create "DemoKeyValue\DefaultIcon" entry ****/
    /*******************************************************/
    Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

    key2.CreateSubKey("Classes");
    key2 = key2.OpenSubKey("Classes", true);

    key2.CreateSubKey("DemoKeyValue");
    key2 = key2.OpenSubKey("DemoKeyValue", true);

    key2.CreateSubKey("DefaultIcon");
    key2 = key2.OpenSubKey("DefaultIcon", true);
    key2.SetValue("", "\"" + "(The icon path you desire)" + "\""); // Set default key value

    key2.Close();

    /**************************************************************/
    /**** Key3: Create "DemoKeyValue\shell\open\command" entry ****/
    /**************************************************************/
    Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);

    key3.CreateSubKey("Classes");
    key3 = key3.OpenSubKey("Classes", true);

    key3.CreateSubKey("DemoKeyValue");
    key3 = key3.OpenSubKey("DemoKeyValue", true);

    key3.CreateSubKey("shell");
    key3 = key3.OpenSubKey("shell", true);

    key3.CreateSubKey("open");
    key3 = key3.OpenSubKey("open", true);

    key3.CreateSubKey("command");
    key3 = key3.OpenSubKey("command", true);
    key3.SetValue("", "\"" + "(The application path you desire)" + "\"" + " \"%1\""); // Set default key value

    key3.Close();
}
Run Code Online (Sandbox Code Playgroud)

只是告诉你们一个快速的演示,非常容易理解.您可以修改这些键值,一切都很好.


小智 5

下面的代码是一个应该可以工作的函数,它在 Windows 注册表中添加所需的值。通常我在可执行文件中运行 SelfCreateAssociation(".abc") 。(形成构造函数或 onload 或 onshown)每次执行可执行文件时,它将更新当前用户的注册表项。(如果您有一些更改,则有利于调试)。如果您需要有关所涉及的注册表项的详细信息,请查看此 MSDN 链接。

https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx

获取有关常规 ClassesRoot 注册表项的更多信息。请参阅这篇 MSDN 文章。

https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx

public enum KeyHiveSmall
{
    ClassesRoot,
    CurrentUser,
    LocalMachine,
}

/// <summary>
/// Create an associaten for a file extension in the windows registry
/// CreateAssociation(@"vendor.application",".tmf","Tool file",@"C:\Windows\SYSWOW64\notepad.exe",@"%SystemRoot%\SYSWOW64\notepad.exe,0");
/// </summary>
/// <param name="ProgID">e.g. vendor.application</param>
/// <param name="extension">e.g. .tmf</param>
/// <param name="description">e.g. Tool file</param>
/// <param name="application">e.g.  @"C:\Windows\SYSWOW64\notepad.exe"</param>
/// <param name="icon">@"%SystemRoot%\SYSWOW64\notepad.exe,0"</param>
/// <param name="hive">e.g. The user-specific settings have priority over the computer settings. KeyHive.LocalMachine  need admin rights</param>
public static void CreateAssociation(string ProgID, string extension, string description, string application, string icon, KeyHiveSmall hive = KeyHiveSmall.CurrentUser)
{
    RegistryKey selectedKey = null;

    switch (hive)
    {
        case KeyHiveSmall.ClassesRoot:
            Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension).SetValue("", ProgID);
            selectedKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProgID);
            break;

        case KeyHiveSmall.CurrentUser:
            Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Classes\" + extension).SetValue("", ProgID);
            selectedKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Classes\" + ProgID);
            break;

        case KeyHiveSmall.LocalMachine:
            Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\Classes\" + extension).SetValue("", ProgID);
            selectedKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"Software\Classes\" + ProgID);
            break;
    }

    if (selectedKey != null)
    {
        if (description != null)
        {
            selectedKey.SetValue("", description);
        }
        if (icon != null)
        {
            selectedKey.CreateSubKey("DefaultIcon").SetValue("", icon, RegistryValueKind.ExpandString);
            selectedKey.CreateSubKey(@"Shell\Open").SetValue("icon", icon, RegistryValueKind.ExpandString);
        }
        if (application != null)
        {
            selectedKey.CreateSubKey(@"Shell\Open\command").SetValue("", "\"" + application + "\"" + " \"%1\"", RegistryValueKind.ExpandString);
        }
    }
    selectedKey.Flush();
    selectedKey.Close();
}

 /// <summary>
    /// Creates a association for current running executable
    /// </summary>
    /// <param name="extension">e.g. .tmf</param>
    /// <param name="hive">e.g. KeyHive.LocalMachine need admin rights</param>
    /// <param name="description">e.g. Tool file. Displayed in explorer</param>
    public static void SelfCreateAssociation(string extension, KeyHiveSmall hive = KeyHiveSmall.CurrentUser, string description = "")
    {
        string ProgID = System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.FullName;
        string FileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
        CreateAssociation(ProgID, extension, description, FileLocation, FileLocation + ",0", hive);
    }
Run Code Online (Sandbox Code Playgroud)


Ste*_*gan 2

文件关联在注册表中的 HKEY_CLASSES_ROOT 下定义。

这里有一个 VB.NET 示例,您可以轻松地将其移植到 C#。