How to run your C# Application as Administrator in Windows Vista?
26 August 2007To have your C# (or any .NET program) run as Administrator in Windows, you'll have to create a manifest for it. What is a manifest file? I think Microsoft explains it best:
Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. (link to the entire MSDN article)
With a Manifest you're able to tell Windows Vista that your C# program wants to run as Administrator. This will cause the Vista confirmation window to pop up asking the user to grant the program access. Running as Administrator in Vista is required, for example, if your program is trying to create a WCF endpoint.
The following manifest XML tells the .NET Framework to run the Assembly that you specify as Administrator within Windows Vista:
-
<?xml version="1.0" encoding="utf-8" ?>
-
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
-
<assemblyIdentity version="1.0.0.0"
-
processorArchitecture="X86"
-
name="someExecName"
-
type="win32" />
-
<description>Your Program Description</description>
-
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security>
-
<requestedPrivileges>
-
<requestedExecutionLevel level="requireAdministrator" />
-
</requestedPrivileges>
-
</security>
-
</trustInfo></assembly>
Now, there are two ways to make your program use this Manifest:
- Rename it to (YourEXEName).manifest. The .NET Framework when executing the file will see the Manifest and handle its contents.
- Embed the .manifest file into you EXE. This can be done by executing the following command line:
- mt -manifest YourProgram.exe.manifest -outputresource:YourProgram.exe
- If your assembly is strong named, you will be unable to embed the manifest into it as it would invalidate the strong naming.
Now your own C# application will prompt to run as Administrator in Windows Vista!
Cheers!
2 Responses to “How to run your C# Application as Administrator in Windows Vista?”
March 20th, 2008 at 3:49 am
Can we disable Windows Vista confirmation popup and set it programatically?
Also I want to run my C# application as administrator only once and then after I want it to run as normal user.
July 4th, 2008 at 8:25 am
Thanks for your post, its very much useful.