ChatGPT解决这个技术问题 Extra ChatGPT

How do I force my .NET application to run as administrator?

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?

Besides what Binary Worrier wrote, you might want to write some code to test if you have admin privileges .. (is that what you are asking for?)
I would not take this task lightly though, you should verfiy what it actually needs admin for and see if you can work around it. No customer is going to be happy running an app in admin mode all the time. Alot of bigger customers won't even consider an app like that, and if logo testing matters to you it will not pass like that.
Alex is very much on point. If possible, only elevate when necessary, otherwise, Group Policy, UAC and a number of other variables come into play. At the very least, with UAC, the user would have to authorize on every run as opposed to only when a specific user action is performed.
The correct way is to embedd a manifest file into your application.

H
Hans Passant

You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:

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

The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.


If you get a ClickOnce error when trying to compile, see this answer: stackoverflow.com/questions/11023998/…
Your project has to be set up to use the app manifest too - in Project Properties, check the "Application" tab and make sure the "Manifest:" under 'Resources" is set to your app.manifest (or whatever you named the .manifest file).
I had to reload the project before VS would prompt me to restart in admin mode.
@Alejandro - Yes, UAC can be disabled, but when that is, the app will automatically run as administrator (assuming your user has administrator privileges), because disabling UAC means everything runs at the highest privilege the user is allowed. It's kind of like complaining that if you install a fancy lock on the door, it won't work if the door is removed.
@ErikFunkenbusch It won't "automatically run as administrator", it'll run under the normal permissions of the user (admin if the user is admin, or standard if the user is standard). Relying on that particular case, even if it's the default, is what good programs will avoid like the plague. Following your analogy, the fancy lock is nice and all, but properly designed software must anticipate the case that the whole door is removed, even if it's a rare occurrence.
H
Hakan Fıstık

Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).


You could also use <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> as well
@MarkKram: What does highestAvailable have to do with this? The question is about forcing admin, highestAvailable is less restrictive than requireAdministrator and will let a non-admin user start the app un-elevated with no UAC prompt, only admins will get prompted...
I don't remember the exact details anymore but I think this depends on what you mean by disabled. Putting the "UAC slider" all the way to the bottom is not the same as disabling UAC (except on Vista). If UAC is fully disabled the whole integrity level mechanism is disabled and only the classic runas.exe feature from 2000/XP is available. The admin role check handles the runas.exe case.
I have set EnableLUA to 0 on Server 2008 R2 and removed myself from the Administrators group, rebooted, and now an exe that specifies level="requireAdministrator" runs without any prompt
T
Termininja

The detailed steps are as follow.

Add application manifest file to project Change application setting to "app.manifest" Update tag of "requestedExecutionLevel" to requireAdministrator.

https://i.stack.imgur.com/5DeDz.png

https://i.stack.imgur.com/tmaVc.png

https://i.stack.imgur.com/bkdgo.png

https://i.stack.imgur.com/nyJPq.png

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security


New Item... isn't an option on my Installer Service project. How would I go about adding the app manifest? I can add it to my main project but not it's installer.
P
Peter Mortensen

I implemented some code to do it manually:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

This only detects if the context is running as Admin it does not forec the application to run as Admin as requested by the OP
I don't think there is any programmatic way to force an application to elevate its own perms. If there were, that would be quite the security risk, no?
Although your solution is good but question was different. ;)
see a refactored version of this method here stackoverflow.com/a/50186997 (subjective)
This does not answer the question!
P
Peter Mortensen

You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).


P
Peter Mortensen

While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.

In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:

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

OR

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

OR

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

To set your application to run as administrator, you have to chose the middle one.


This works. However, it made a blank cmd window appear when running the CMD application (using c# cmd app to run some exe in the background).
C
Community

Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

private static void Main(string[] args)
{
    if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        foreach (string arg in args)
        {
            proc.Arguments += String.Format("\"{0}\" ", arg);
        }

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
        }
        catch
        {
            Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
        }
    }
    else
    {
        //Normal program logic...
    }
}

private static bool IsRunAsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);

    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

+1 for code-only approach. Note that you need UAC enabled for having a chance to launch anything with runas as administrator from a non-admin user, otherwise it will open silently with current user permissions (checked on windows 7 64 bit). As far as I can tell the only thing you can do with UAC disabled and the admin right is missing is to stop execution in a proper moment.
P
Peter Mortensen

As per

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

you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.

Next, right click project

Add new Item

Last, find and click Application Manifest File


E
Evolved

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.


This answer is about VB.NET :-) , not VS 2010 in general. The "Add New Item" answers are about C#. In C++ you can do it in project settings.
Y
Yochai Timmer

You can create the manifest using ClickOnce Security Settings, and then disable it:

Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings

After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option

Open that file and change this line :

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

to:

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

This will make the program require administrator privileges.


H
Hakan Fıstık

THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by @NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}

This does not answer the question!
@Elmue it is more logical to add your comment to the original answer that I just refactored, you can find a link to that answer in mine.
G
Gaspa79

In case you want a code-only solution for some reason, here's a standalone class file. Just call "AdminRelauncher.RelaunchIfNotAdmin()" at application start:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;

public static class AdminRelauncher
{
    public static void RelaunchIfNotAdmin()
    {
        if (!RunningAsAdmin())
        {
            Console.WriteLine("Running as admin required!");
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Assembly.GetEntryAssembly().CodeBase;
            proc.Verb = "runas";
            try
            {
                Process.Start(proc);
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
                Environment.Exit(0);
            }
        }
    }

    private static bool RunningAsAdmin() 
    {
        WindowsIdentity id = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(id);

        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

S
SlickJayD

Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.

If you want to run it as admin for all users, do the same thing in 'change setting for all users'.


This doesn't answer the question. "Once my program is installed on a client machine", not "how do I".
Sorry for being unclear. Once your program is installed, change this setting in your executable's properties (your main program, not the installer). He does want to force his program to run as admin.
Its better to set the admin requirement in the manifest. I'd argue it answers the question, but just barely.
@Joe To be fair, the accepted answer doesn't answer the OPs question as requires you to reinstall the application exe. That's hardly a solution for "Once my program is installed". If anything this downvoted answer is more correct than the accepted answer, so I don't understand why that answer has 400+ votes.
Actually, it answers both questions perfectly. Not much chance of changing the manifest once installed and programs should not try to elevate their permissions once running -- in many environments -- it is a good path to being called malware. In most companies -- this answer is the best because it puts the onus on the user and their permissions. I write a lot of code that I can neither "see" or run once it is in production. Try not to be more clever than your own security concerns are.