Create key in windows registry without permission in c#

Asked

Viewed 1,238 times

3

My application needs to insert itself into the Windows Defender exclusions. Simply create a Myapp.exe key on the way {HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes}, but it is by returning the message stating that I do not have permission.

I am machine administrator user and my application is running as administrator but the error is the same.

Windows 8.1 and 10 have their own command that can be run by Power Shell, but Windows 7 does not. They can help me?

Follow the code I’m using:

RegistryKey localRaiz;
RegistryKey key;

try
{
    string path = @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes";
    localRaiz = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

    key = localRaiz.OpenSubKey(path);
    key.SetValue("MPI.exe", 0, RegistryValueKind.DWord);
    key.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

2 answers

2

You have to open the key in the mode "writable", for this just change

key = localRaiz.OpenSubKey(path);

for

key = localRaiz.OpenSubKey(path, true);

Reference: Registrykey.Opensubkey method

  • had already tried this way. Thus the visual studio returns me the following error message: "Access to the requested Record is not allowed". Remembering that I am the machine administrator and my application runs as an administrator.

1

Run VS as administrator and your application as administrator

public static  bool GravarRegistroUsersSoftware(string Subchave, string nomevalor, string valor)
{
   try
   {
       // cria uma referêcnia para a chave de registro Software
       RegistryKey rk = Registry.Users.OpenSubKey(".DEFAULT\\Software", true);

       // cria um Subchave como o nome GravaRegistro
       rk = rk.CreateSubKey(Subchave);

       // grava o caminho na SubChave GravaRegistro
       rk.SetValue(nomevalor, valor);

       // fecha a Chave de Restistro registro
       rk.Close();

       return true;
   }

   catch (Exception except)
   {
       UltimoErro = except.Message;
       return false;
   }
}

public static  string LerRegistroUsersSoftware(string Subchave, string nomevalor)
{
   try
   {
       string tmpstr = null;
       // cria uma referêcnia para a chave de registro Software
       RegistryKey rk = Registry.Users.OpenSubKey(".DEFAULT\\Software", true);

       // realiza a leitura do registro
       tmpstr = rk.OpenSubKey(Subchave, true).GetValue(nomevalor).ToString();
       return tmpstr;
   }

   catch (Exception except)
   {
       UltimoErro = except.Message;
       return null;
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.