/// <summary> /// Removes the association of the specifed file type with the client. /// </summary> /// <param name="p_fasFileAssociation">The description of the file type association to remove.</param> /// <exception cref="InvalidOperationException">Thrown if the user does not have sufficient priviledges /// to remove the association.</exception> protected void UnassociateFile(FileAssociationSetting p_fasFileAssociation) { if (!UacUtil.IsElevated) throw new InvalidOperationException("You must have administrative privileges to change file associations."); string strFileId = p_fasFileAssociation.Extension.TrimStart('.').ToUpperInvariant() + "_File_Type"; string[] strKeys = Registry.ClassesRoot.GetSubKeyNames(); if (Array.IndexOf<string>(strKeys, strFileId) != -1) { Registry.ClassesRoot.DeleteSubKeyTree(strFileId); Registry.ClassesRoot.DeleteSubKeyTree(p_fasFileAssociation.Extension); } }
/// <summary> /// Associates the specifed file type with the client. /// </summary> /// <param name="p_fasFileAssociation">The description of the file type association to create.</param> /// <exception cref="InvalidOperationException">Thrown if the user does not have sufficient priviledges /// to create the association.</exception> protected void AssociateFile(FileAssociationSetting p_fasFileAssociation) { if (!UacUtil.IsElevated) throw new InvalidOperationException("You must have administrative privileges to change file associations."); string strFileId = p_fasFileAssociation.Extension.TrimStart('.').ToUpperInvariant() + "_File_Type"; try { Registry.SetValue(@"HKEY_CLASSES_ROOT\" + p_fasFileAssociation.Extension, null, strFileId); Registry.SetValue(@"HKEY_CLASSES_ROOT\" + strFileId, null, p_fasFileAssociation.Description, RegistryValueKind.String); Registry.SetValue(@"HKEY_CLASSES_ROOT\" + strFileId + @"\DefaultIcon", null, Application.ExecutablePath + ",0", RegistryValueKind.String); Registry.SetValue(@"HKEY_CLASSES_ROOT\" + strFileId + @"\shell\open\command", null, "\"" + Application.ExecutablePath + "\" \"%1\"", RegistryValueKind.String); } catch (UnauthorizedAccessException) { throw new InvalidOperationException("Something (usually your antivirus) is preventing the program from interacting with the registry and changing the file associations."); } }