How to force my C# Winforms program run as administrator on any computer ? and any kind of OS ?
I need code solution (any sample code will be excell
The obvious answer is to add a manifest file to the C# project and add the following line:
But, a rather unorthodox approach can also be taken. We know that registry access requires administrator privileges. So, if you have a function that contains a registry write access, the function will throw a System.Security.SecurityException if you don't run the program as an administrator. It is implied that you have to call this function at the beginning of the program. If this exception is thrown, you can inform the user to run the program as an administrator and close the program.
public void enforceAdminPrivilegesWorkaround()
{
RegistryKey rk;
string registryPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\";
try
{
if(Environment.Is64BitOperatingSystem)
{
rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
}
else
{
rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
}
rk = rk.OpenSubKey(registryPath, true);
}
catch(System.Security.SecurityException ex)
{
MessageBox.Show("Please run as administrator");
System.Environment.Exit(1);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
Here, the true in line rk = rk.OpenSubKey(registryPath, true) tells the program that it needs write access to the registry.