What is the easiest way to execute a method with administrator privileges?

I am currently just calling my own program in a new process with

MyProcessStartInfo.Verb = "runas"; MyProcessStartInfo.Arguments = "MyFlag"; 

And when the process begins, I check the flag. If it is there - I just execute the method and Close();

But I would rather do something more minimalistic if it could be done simply. Is it possible?

EDIT: Using Vista and Windows7.

+1
source share
3 answers

You cannot raise the current process. It is simply not possible. You are doing it right by creating another process with elevated privileges. There is no other way.

Thanks. but I was thinking maybe there is a way to start the method as a new process.

You can create a separate application executable file that has its own method, then you will not need to restart the application. You will only need to start this other process.

+2
source

This is not minimalistic, but you can use this property that I created from sources on the network. Some of these calls are pInvoke. So google 'pinvoke method' to find them.

 public static bool IsRunAsAdministrator { get { WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity.IsSystem) return true; WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity); if (windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) return true; //Vista or higher check if (Environment.OSVersion.Version.Major >= 6) { IntPtr hToken = IntPtr.Zero; try { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out hToken)) Win32.ThrowLastError(); TOKEN_ELEVATION_TYPE elevationType; IntPtr pElevationType = Marshal.AllocHGlobal(sizeof(TOKEN_ELEVATION_TYPE)); uint dwSize; if (!GetTokenInformation( hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, sizeof(TOKEN_ELEVATION_TYPE), out dwSize )) Win32.ThrowLastError(); elevationType = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(pElevationType); Marshal.FreeHGlobal(pElevationType); return elevationType == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull; } finally { CloseHandle(hToken); } } else return true; } } 
+1
source

You can use the Windows API LogonUser , and then impersonate another user to run part of the code as that user. However, there is a limitation. When UAC is turned on, LogonUser will give you a limited user token, which means that the logged out user (even the administrator) will never get more rights than you already have. This restriction does not apply to non-interactive sessions (Windows Services).

Here is the documentation on how to personalize code. Alternatively, you can find this SO question / answer .

0
source

Source: https://habr.com/ru/post/915730/


All Articles