3

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?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Erin
  • 2,407
  • 18
  • 21

3 Answers3

2

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.

Community
  • 1
  • 1
Ryan
  • 23,871
  • 24
  • 86
  • 132
1

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.

Community
  • 1
  • 1
Ray
  • 45,695
  • 27
  • 126
  • 169
0

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
  • 3,392
  • 1
  • 31
  • 54
  • I don't think this will work for the desktop but it is still going to be useful for other projects. – Erin Oct 30 '08 at 13:44