-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFileAssociation.cs
76 lines (72 loc) · 3.2 KB
/
FileAssociation.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
namespace Setup
{
/// <summary>
/// This class conatins methods for registring/unregistring a file extension
/// </summary>
public static class FileAssociation
{
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
/// <summary>
/// Associates a file extension with your program
/// </summary>
/// <param name="name">Simply the name of the program, e.g. Test</param>
/// <param name="extension">The extension, e.g. ".def"</param>
/// <param name="icon">The path of the icon</param>
/// <param name="path">The path of the programm</param>
/// <returns>Whether it has worked or not</returns>
public static bool SetFileAssociation(string name, string extension, string icon, string path)
{
try
{
Registry.ClassesRoot.CreateSubKey(extension).SetValue(string.Empty, name);
RegistryKey key = Registry.ClassesRoot.CreateSubKey(name, RegistryKeyPermissionCheck.ReadWriteSubTree);
key.SetValue(string.Empty, name, RegistryValueKind.String);
key.CreateSubKey("DefaultIcon").SetValue(string.Empty, icon, RegistryValueKind.String);
key.CreateSubKey(@"Shell\Open\Command").SetValue("", "\"" + path + "\" \"%1\"", RegistryValueKind.String);
key = key.CreateSubKey("OpenWithList", RegistryKeyPermissionCheck.ReadWriteSubTree);
key.CreateSubKey(name);
key.Flush();
key.Close();
FileAssociation.SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Remove the association which you have created
/// </summary>
/// <param name="name">Name of your program, e.g. Test</param>
/// <param name="extension">The extension of your file, e.g. ".def"</param>
/// <returns>Whether it has worked or not</returns>
public static bool RemoveFileAssociation(string name, string extension)
{
try
{
if (Registry.ClassesRoot.OpenSubKey(extension, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl) != null)
{
Registry.ClassesRoot.DeleteSubKeyTree(Registry.ClassesRoot.OpenSubKey(extension, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl).GetValue("").ToString());
Registry.ClassesRoot.DeleteSubKeyTree(extension);
FileAssociation.SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
return true;
}
else
return false;
}
catch (Exception)
{
return false;
}
}
}
}