Как удалить ключи с локальной машины \ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ? - PullRequest
0 голосов
/ 23 октября 2018

Я пытался удалить тестовый ключ через скрипт C #.Следующий код - мой скрипт, я также добавил значение admin в файл манифеста для этого UAC проекта.Но это все еще не работает.Даже перезапустил Visual Studio 2017 с режимом администратора.В сообщении об ошибке говорится, что невозможно записать в раздел реестра.Не уверен, что не так в сценарии.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;


namespace temp_code_tester
{
class Program
{
    static void Main(string[] args)
    {
        //Get current login account info from another Class
        //string userName = WindowsIdentity.GetCurrent().Name;
        //var SecCheck = new SecutriyProcesser();
        //SecCheck.AddRule(userName);


        var RunCheck = new AccessRegistry();
        RunCheck.ACL("Test");

    }
}

class AccessRegistry
{
    public void ACL(string name)
    {
        Console.WriteLine("Getting the registry keys.....");
        Console.WriteLine("---------------------------------------------\n");

        //Open the SOFTWARE keys and input those keys into array
        RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE");
        string[] lists = SoftKey.GetSubKeyNames();

        foreach (string KeyName in lists)
        {
            Console.WriteLine(KeyName);
        }

        foreach (string value in lists)
        {
            if (value.Contains(name)) // if we find the key, then lists all subkeys
            {
                //Registry.LocalMachine.DeleteSubKeyTree(value);
                Console.WriteLine("\nMatch one: {0}", value);

                var RightKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\" + value);
                string[] SubList = RightKey.GetSubKeyNames();

                foreach (string SubValue in SubList)
                {
                    Console.WriteLine("Folder: {0} is under this key", SubValue);
                }

                if (SubList.Length > 1)
                {
                    try
                    {
                        SoftKey.DeleteSubKeyTree(value);
                        Console.WriteLine("\nThe folder {0} has been removed", value);
                    }
                    catch (Exception er)
                    {
                        Console.WriteLine("Error: {0}", er.Message);
                    }
                }
                else
                {
                    try
                    {
                        SoftKey.DeleteSubKey(value);
                    }
                    catch (Exception)
                    {
                        throw;
                    }

                }
            }
        }
        SoftKey.Close();
    }
}

class SecutriyProcesser
{
    // A method about add enough roles for current window account
    public void AddRule(string userName)
    {
        RegistrySecurity rs = new RegistrySecurity();
        rs.AddAccessRule(new RegistryAccessRule(userName,
            RegistryRights.FullControl,
            InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow));
    }

    // Try to list the security level
    public void ShowSecurity(RegistrySecurity security)
    {
        Console.WriteLine("\r\nCurrent access rules:\r\n");

        foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
        {

            Console.WriteLine("        User: {0}", ar.IdentityReference);
            Console.WriteLine("        Type: {0}", ar.AccessControlType);
            Console.WriteLine("      Rights: {0}", ar.RegistryRights);
            Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
            Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
            Console.WriteLine("   Inherited? {0}", ar.IsInherited);
            Console.WriteLine();
        }

    }
  }
}

1 Ответ

0 голосов
/ 23 октября 2018

Вы забыли параметр «доступный для записи» метода «OpenSubkey».Попробуйте это:

RegistryKey SoftKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE", true);

Это должно работать следующим образом.

РЕДАКТИРОВАТЬ: Этот метод, вероятно, не удастся, если вы не запускаете Visual Studio как администратор во время отладки.

...