Repository navigation
Expand file tree
/
Copy pathFileAssociationHelper.cs
More file actions
54 lines (48 loc) · 2.03 KB
/
Copy pathFileAssociationHelper.cs
File metadata and controls
54 lines (48 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using Microsoft.Win32;
namespace LinView
{
/// <summary>
/// 负责系统级文件关联的读写(需要管理员权限)。
/// </summary>
public static class FileAssociationHelper
{
/// <summary>把某个扩展名关联到本程序。</summary>
public static void Associate(string ext)
{
string exePath = System.Windows.Forms.Application.ExecutablePath;
// 1. 注册 ProgID
using (var progId = Registry.ClassesRoot.CreateSubKey(AppConstants.ProgId))
{
progId.SetValue("", AppConstants.ProgIdDescription);
using var icon = progId.CreateSubKey("DefaultIcon");
icon.SetValue("", $"\"{exePath}\",0");
using var cmd = progId.CreateSubKey(@"shell\open\command");
cmd.SetValue("", $"\"{exePath}\" \"%1\"");
}
// 2. 把扩展名默认指向 ProgID
using (var extKey = Registry.ClassesRoot.CreateSubKey(ext))
{
extKey.SetValue("", AppConstants.ProgId);
}
// 3. 同时写入 OpenWithProgids,保证"打开方式"列表里也有
using (var openWith = Registry.ClassesRoot.CreateSubKey($@"{ext}\OpenWithProgids"))
{
openWith.SetValue(AppConstants.ProgId, Array.Empty<byte>(), RegistryValueKind.None);
}
}
/// <summary>取消某个扩展名与本程序的关联。</summary>
public static void Unassociate(string ext)
{
using (var extKey = Registry.ClassesRoot.OpenSubKey(ext, writable: true))
{
if (extKey?.GetValue("") as string == AppConstants.ProgId)
extKey.DeleteValue("", throwOnMissingValue: false);
}
using (var openWith = Registry.ClassesRoot.OpenSubKey($@"{ext}\OpenWithProgids", writable: true))
{
openWith?.DeleteValue(AppConstants.ProgId, throwOnMissingValue: false);
}
}
}
}