views:

235

answers:

3

I have a program that needs to run as a normal user most of the time 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.

A: 

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.

Andrew Theken
I don't think this will work for the desktop but it is still going to be useful for other projects.
Erin
This is patently wrong.
Paul Betts
+1  A: 

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.

Ray
+2  A: 

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.

Ryan