Question

I have a program that needs to run as a normal user most of the time, but once in a while I need to stop and start a service. How do I go about making a program that runs as a normal user most of the time but elevates into administrator mode for some function?

Was it helpful?

Solution

As far as I know, you need to start a seperate process that runs as the administrator. You can't elevate a process once it's already been started.

See this question.

OTHER TIPS

You can't elevate a process once its running but you could either :-

Restart the process as elevated

private void elevateCurrentProcess()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.UseShellExecute = true;
    startInfo.WorkingDirectory = Environment.CurrentDirectory;       
    startInfo.FileName = Application.ExecutablePath;
    startInfo.Verb = "runas";

    try
    {
        Process p = Process.Start(startInfo);
    }
    catch
    {
        // User didn't allow UAC
        return;
    }
    Application.Exit();
}

This method means that your process continues to run elevated and no more UAC promopts - both a good and a bad thing, depends upon your audience.

Put the code that requires elevation into a seperate exe

Set the manifest as requireAdministrator and start it as a separate process. See this sample code

This method means a UAC prompt every time you run the operation.

Best method depends upon your audience (admin types or not) and frequency of the elevated operation.

You need to use what is referred to as Impersonation..

[http://support.microsoft.com/kb/306158][1]

The above shows how it would be accomplished for an ASP.Net app, but the code is probably near identical for your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top