[C#][Reproduced] Registry access read and write permissions solution

[VS debugging] C# throws "the requested registry access is not allowed" solution when reading and writing Windows 7 registry

Project-Properties-Security, "Use ClickOnce", modify app.mainfest, and then cancel "Use ClickOnce"

 

[Another reference article: http://blog.csdn.net/wonsoft/article/details/6598407 ]

 

    A program that has been debugged well under XP/2003, but under windows7, throws an exception of "Access to the requested registry is not allowed", which is triggered when reading and writing the registry, for example:

public class Program
    {
        public static void SetAutoRun(string keyName, string filePath)
        {
            using (RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"software\microsoft\windows\currentversion\run", true))
            {
                runKey.SetValue(keyName, filePath);
                runKey.Close();
            }
        }
 
        static void Main()
        {
            string keyName = "TestAutoRun";
            string fliePath = @"D:\CSharpProject\CSharp_Learn\MyDelegate.exe";
            SetAutoRun(keyName, fliePath);
        }
    }
}

If the program runs under windows 7, it needs to be run with administrator privileges.

 

【method one】

Registry

The code access security policy must grant RegistryPermission to code that uses the Microsoft.Win32.Registry class to access the registry. This permission type can be used to restrict registry access to specific registry keys and sub-registry keys. It can also control the code's ability to read, write, or create registry keys and named values.

Constrain registry access

To restrict code access to specific registry keys, you can use RegistryPermissionAttribute with SecurityAction.PermitOnly. The following attributes ensure that the code can only read the YourApp registry key (and subkeys) under HKEY_LOCAL_MACHINE\SOFTWARE.

[RegistryPermissionAttribute(SecurityAction.PermitOnly,
Read=@"HKEY_LOCAL_MACHINE\SOFTWARE\YourApp")]
public static string GetConfigurationData( string key, string namedValue )
{
return (string)Registry.
LocalMachine.
OpenSubKey(key).
GetValue(namedValue);
}

To record the permission requirements of the code, and to ensure that the assembly cannot be loaded when the code access security policy does not grant it sufficient registry access permissions, an assembly-level RegistryPermissionAttribute with SecurityAction.RequestMinimum should be added, as shown in the following example.

 

[assembly:RegistryPermissionAttribute(SecurityAction.RequestMinimum,
Read=@"HKEY_LOCAL_MACHINE\SOFTWARE\YourApp")]

【Method Two】

Add the application manifest file and add it

<security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC checklist option
            If you want to change the Windows user account control level, please replace the
            requestedExecutionLevel node with one of the following  nodes.
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
            If you want to use files and registration forms Virtualization provides
            backward compatibility, please delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Modify the code as follows:

System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal( identity );
if(principal.IsInRole( System. Security.Principal.WindowsBuiltInRole.Administrator ))
{     // Modify the registry } else {        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();        startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; // Get the path and file name of the current executable file          // The following Args are the corresponding parameters to start the program         startInfo.Arguments = String.Join( "", Args );        startInfo.Verb = "runas";









       System.Diagnostics.Process.Start( startInfo );
}
 

Problem Description:

In order to realize the automatic start of the program, we will write relevant information in the registry. The implementation code is as follows:

RegistryKey HKLM = Registry.LocalMachine;
RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");

 

 

But the error as shown in the picture above is always prompted, which bothered me for a long time. The compiled exe runs as an administrator without any problems, why? Is it that VS does not have an administrator status for debugging (it is not necessary in fact), which is puzzled. . . Finally found that in win7 using vs to access the registry key HKEY_LOCAL_MACHINE does not work without administrator status, but access to HKEY_CURRENT_USER is OK, so the above code is modified to:

RegistryKey HKLM = Registry.CurrentUser;
RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");

It's OK now.

 

 

Reference: "Windows 7 software development example: UAC, system version, permissions"


 

 

Seeing the cool features of Win7 drooling, can't help but want to embrace it? Don't worry, Win7 has a bad temper. If we want to embrace its new features, our software must be married to it-it can run normally under Win7. , The small and medium software developed by individual developers has relatively simple functions and generally low degree of closeness with the system. Adding some elements necessary for normal operation of Win7 is OK!

  Necessary conditions for marrying Win7

  What we have to add to the software are system version detection and installation path selection elements. Why should we consider them?

  Prerequisite 1: Check the system version

  The software needs to determine the type and version number of the operating system at the early stage of operation , and execute specific codes according to the type of operating system. The same function may execute different codes on different operating systems. The failure of most software to run normally under Win7 is caused by the failure to determine the operating system version.

  When the version detection error occurs, many software will also follow the error. The user may find that after double-clicking the software picture, nothing is reflected, or may see a dialog box "You must be running on Microsoft Windows  XP or newer version", but in reality Win7 has been installed on the computer.

  Necessary Condition 2: Adapt to user permissions

  Win7 runs a non-administrator account by default, with relatively small permissions. The software installation program will write some data to the Program Files including the system disk, the Windows installation directory, and the registry (the software may save some user data to the system folder or registry when the software is running). If the current user If the permission of is not enough, the software cannot enter Win7 normally.

  Tips: UAC is a way to reduce the default permissions of Windows users, which will improve the security of users. It can prevent the outbreak of some viruses to a certain extent -turn off anti-virus software, start replication and spread virus processes, Inject online game clients and monitor keyboard operations to steal passwords.

  For example, the data seems to be saved successfully but cannot be found at the location where it was written, or when logging out and switching to another Windows user, the saved data cannot be found. The root cause of this kind of problem is Win7's UAC mechanism, which reduces the default permissions of Windows users, making it impossible to change the system settings and system protected folders for some common operations.

  Tips: When the software needs to integrate certain functions of the system, it needs to call the corresponding API. Whether the API is called properly or not is very important to the operation of the software. From the next issue, we will combine the cool features of Win7 to separately introduce how to call it correctly. The latest Win7 API, including Win7-specific taskbar personalized shortcut menu (Jump List), program icon outline effect (Icon Overlay), program icon progress bar effect (Progress Bar), tabbed thumbnail (Tabbed Thumbnail) and thumbnail Thumbnail Toolbar...

  Essential elements for "wedding"

  Our software wants to marry Win7 smoothly, and the following elements should be added to the software.

  1. Code detection operating system version number

  Add the code to determine whether the operating system is Win7 or 2008 Server in the software:

  C#

 

      if (Environment.OSVersion.Version > new Version(5, 1))
      {MessageBox.Show("Windows 7 or Windows 2008 Server","Operating System", 
                      MessageBoxButtons.OK,MessageBoxIcon.Error);
            return;
      }

 

  2. Try to store data in a non-system disk

  The software should not be installed to the system disk by default. This should be considered when writing the software installation path. In addition, you need to add code to modify the read and write registry in the software, and use the key value under HKEY_CURRENT_USER\Software as the node for storing data:

 

        static void Main(string[] args)
        {
            var registryKey = Registry.CurrentUser.CreateSubKey(
                @"Software\test");
            registryKey.SetValue("name", "zswang");
            registryKey = Registry.CurrentUser.OpenSubKey(@"Software\test");
            Console.WriteLine(string.Format("{0}={1}\r\n",
               "name", registryKey.GetValue("name")));
        }

 

  3. Improve the operating authority of the program

  What if the user enters the system as an administrator and wants to install the software on the system disk? Need to determine the permissions of the user permissions, the simple solution is to add a manifest file. Find the file with the same name as the executable file and the extension .manifest in the executable folder, and enter the following code:

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> 
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="test"
     type="win32"/> 
  <description>Description of your application</description> 
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

Guess you like

Origin blog.csdn.net/FL1623863129/article/details/113822598