Hello,
You can't make your application run automatically with administrator privileges. But you can easily prompt for elevation requesting the user to allow the application to run with administrator rights.
Here is a way to do it:
First use Win32 to check if the current user has admin rigths:
[DllImport("shell32.dll")]
internal static extern bool IsUserAnAdmin();
Then write a method to elevate your process:
private static bool Elevate(string processPath)
{
bool elevated = false;
if (!IsUserAnAdmin())
{
elevated = true;
ProcessStartInfo procInfo = new ProcessStartInfo(processPath);
procInfo.UseShellExecute = true;
procInfo.Verb = "runas";
procInfo.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(procInfo);
}
return elevated;
}
Finally put it all together:
[DllImport("shell32.dll")]
internal static extern bool IsUserAnAdmin();
public static void Main(string[] args)
{
if (!Elevate(System.Reflection.Assembly.GetExecutingAssembly().Location))
{
const string NO_DRIVE = @"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";
try
{
using (RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(NO_DRIVE))
{
registryKey.SetValue("NoDrives",
Convert.ToInt32("8", 16), RegistryValueKind.DWord);
registryKey.Close();
Console.WriteLine("Successfully Locked");
};
}
catch (UnauthorizedAccessException E)
{
Console.WriteLine("Access not allowed.");
}
Console.ReadLine();
}
}
private static bool Elevate(string processPath)
{
bool elevated = false;
if (!IsUserAnAdmin())
{
elevated = true;
ProcessStartInfo procInfo = new ProcessStartInfo(processPath);
procInfo.UseShellExecute = true;
procInfo.Verb = "runas";
procInfo.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(procInfo);
}
return elevated;
}
What happens is that first time the code is executes, you call a win32 api that tells you if the user has admin rights or not, if not, you run startup your process using the "runas" verb that triggers elevation request and your process is not running as administrator.
There are other way to achieve the same using application manifest etc... Google is your friend...
Valery.