using System.IO;
using Microsoft.Win32;
ProcessFileExtReg(true);
private static void ProcessFileExtReg(bool register)
{
using (RegistryKey classesKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes", true))
{
if (CheckRegistryKeyExists(classesKey, ext)) return;
if (register == true)
{
using (RegistryKey extKey = classesKey.CreateSubKey(ext))
{
extKey.SetValue(null, extType);
}
// or, use Registry.SetValue method
using (RegistryKey typeKey = classesKey.CreateSubKey(extType))
{
typeKey.SetValue(null, fileTypeDesc);
using (RegistryKey shellKey = typeKey.CreateSubKey("shell"))
{
using (RegistryKey openKey = shellKey.CreateSubKey("open"))
{
using (RegistryKey commandKey = openKey.CreateSubKey("command"))
{
string assocExePath = GetProcessPath();
string assocCommand = string.Format("\"{0}\" \"%1\"", assocExePath);
commandKey.SetValue(null, assocCommand);
}
}
}
}
}
else
{
DeleteRegistryKey(classesKey, ext, false);
DeleteRegistryKey(classesKey, extType, true);
}
}
}
private static void DeleteRegistryKey(RegistryKey classesKey, string subKeyName, bool deleteAllSubKey)
{
if (CheckRegistryKeyExists(classesKey, subKeyName) == false)
{
return;
}
if (deleteAllSubKey == true)
{
classesKey.DeleteSubKeyTree(subKeyName);
}
else
{
classesKey.DeleteSubKey(subKeyName);
}
}
private static bool CheckRegistryKeyExists(RegistryKey classesKey, string subKeyName)
{
RegistryKey regKey = null;
try
{
regKey = classesKey.OpenSubKey(subKeyName);
return regKey != null;
}
finally
{
if (regKey != null)
{
regKey.Close();
}
}
}
private static string GetProcessPath()
{
string path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
return Path.Combine(path, assocExeFileName);
}