58

I have an WPF application which access windows services, task schedulers on the local machine. When I deploy this WPF application and run it without "Run as Administrator" , it fails as it is not able to access the windows services and task schedulers on the local machine. If I run it with "Run as Administrator", it works correctly.

How do I make my application by default run in admin mode when it is deployed in production?

SVI
  • 1,631
  • 3
  • 22
  • 30

6 Answers6

89

You need to add an app.manifest. Change the requestedExecutionLevel from asInvoker to requireAdministrator. You can create a new manifest by using the add file dialog, change it to require administrator. Make sure that your project settings are set to use that manifest as well. This will allow you to simply double click the application and it will automatically prompt for elevation if it isn't already.

See here for more documentation:

http://msdn.microsoft.com/en-us/library/bb756929.aspx

EDIT: For what it's worth, the article uses VS 2005 and using mt.exe to embed the manifest. if you are using Visual studio 2008+, this is built in. Simply open the properties of your Project, and on the "Application" tab you can select the manifest.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • 2
    Will this work on Windows 7 as well? There is a note on that page that brings up this question... _In future releases, the only way to run an application elevated will be to have a signed application manifest that identifies the privilege level that the application needs._ – Dean Kuga Mar 11 '11 at 18:32
  • @kzen, as of now - yes - this same procedure will work for Windows 7. – vcsjones Mar 11 '11 at 18:33
  • Will this work if I install my application on Windows Server 2008 machines, that is where I am issues with running my application? – SVI Mar 11 '11 at 20:14
  • VCSJones, I tried adding {MyAppliationName}.exe.Manifest file to the project and when I compile I get an error which seems very common. Error is "ClickOnce does not support the request execution level 'requireAdministrator'." – SVI Mar 11 '11 at 21:15
  • Is your application XBAP or ClickOnce deployed? – vcsjones Mar 11 '11 at 22:31
  • 2
    Thanks VCSJones. Your solution worked for me. I had to disable ClickOnce to get rid of that error. I did this by going to project properties, security tab and unchecking the "Enable ClickOnce security settings" option. – SVI Mar 17 '11 at 21:00
  • When I select the View UAC Settings (app.manifest) and change to I get an error stating "Error 6 ClickOnce does not support the request execution level 'requireAdministrator'. " this is accurate according to MSDN. – Michael Eakins May 13 '11 at 15:21
  • @Michael, ClickOnce doesn't directly support a manifest that can start as an administrator. If you need a clickOnce app to run as an Admin, you should write a bootstrap program to start the other as elevated. – vcsjones May 13 '11 at 15:54
  • @vcsjones I have the found several examples of the hack around WPF, I was actually hoping for something that didn't require the user to approve running as an administrator. Thanks for the reply! – Michael Eakins May 13 '11 at 15:59
  • Can this be used in VS2013 Express? We don't seem to have any deployment method other than ClickOnce. – dotNET Apr 03 '14 at 17:36
30
  1. Right-click your WPF project to add new Item: "Add->New Item..."
  2. Select "Application Manifest File" and click Add
  3. Double Click your newly created manifest file and change the
<requestedExecutionLevel level="asInvoker" uiAccess="false" />

to

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Then the WPF application would run as Administrator.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
SLdragon
  • 1,477
  • 16
  • 19
4

If you don't want broke the Clickonce this code is the best solution:

using System.Security.Principal;
using System.Management;
using System.Diagnostics;
using System.Reflection;
//Put this code in the main entry point for the application
// Check if user is NOT admin 
if (!IsRunningAsAdministrator())
{
    // Setting up start info of the new process of the same application
    ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase);

    // Using operating shell and setting the ProcessStartInfo.Verb to “runas” will let it run as admin
    processStartInfo.UseShellExecute = true;
    processStartInfo.Verb = "runas";

    // Start the application as new process
    Process.Start(processStartInfo);

    // Shut down the current (old) process
    System.Windows.Forms.Application.Exit();
    }
}

/// <summary>
/// Function that check's if current user is in Aministrator role
/// </summary>
/// <returns></returns>
public static bool IsRunningAsAdministrator()
{
    // Get current Windows user
    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

    // Get current Windows user principal
    WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

    // Return TRUE if user is in role "Administrator"
    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

Founded in: http://matijabozicevic.com/blog/wpf-winforms-development/running-a-clickonce-application-as-administrator-also-for-windows-8

Mårshåll
  • 115
  • 1
  • 13
  • That was the only solution without breaking the ClickOne sign and security. if you want to use publish that the solution. – TAO Dec 26 '20 at 20:25
4

Steps to Make the WPF application to Run in Administrator Mode

1.Open the Solution Explorer

2.Right CLick on the solution--->Add---->New Item---->App.Manifest---->OK

3.Edit the Manifest file as follows:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

(TO)

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

4.After editing the Manifest file,Goto Solution project(RightCLick)------>properties------->Security

Turn out the Checkbox of "Enable ClickOnce Security Settings"

  1. Run the Application, and Take setup, Now the application with Run as Administrator mode is acheived.
  • What if step 2 doesn't have App.Manifest to select? I don't know what's going on with my project but I really don't have manifest file to select using visual studio 2019 with WPF c# – Noryn Basaya Jul 03 '21 at 18:56
  • @NorynBasaya It's there for me, it's named 'Application Manifest File'. – LiamJM Aug 18 '23 at 12:57
1

WPF App.xaml.cs
Current application process will kill and same application with new process as run as administrator will going to launch.

public partial class App : Application
{
        //This function will be called on startup of the applications
        protected override void OnStartup(StartupEventArgs e)
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false && principal.IsInRole(WindowsBuiltInRole.User) == true)
            {
                ProcessStartInfo objProcessInfo = new ProcessStartInfo();
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.FileName = Assembly.GetEntryAssembly().CodeBase;
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.Verb = "runas";
                try
                {
                    Process proc = Process.Start(objProcessInfo);
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                }
            }
        }
}
Sandeep Jadhav
  • 815
  • 1
  • 10
  • 27
0

I found this code helping me to do it in the right way I want.

I want the app run "By the USER choois as administrator" not making the app itself run itself as administrator.

This method forces the user to run the app as administrator

So this is my code at last

public partial class App : Application
{
    public static bool IsUserAdministrator()
    {
        try
        {
            WindowsIdentity user = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(user);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch
        {
            return false;
        }
    }

    protected override void OnStartup(StartupEventArgs e)
    {

        if (!IsUserAdministrator())
        {

            //TODO if NOT RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("not admin");
            Application.Current.Shutdown();
        }
        else
        {
            //TODO if RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("Admin");
        }

    }

}