tags:

views:

86

answers:

3

hi

how to force my C# Winforms program run as administrator on any computer ?

and any kind of OS ?

i need code solution (any sample code will be excellent)

thank's in advance

+7  A: 

You can embed this manifest into your application.

<?xml version="1.0" encoding="utf-8" ?> 
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
    <assemblyIdentity version="1.0.0.0" name="MyApplication" />
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
            <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
                <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
            </requestedPrivileges>
        </security>
    </trustInfo>
</asmv1:assembly>  
Alex Reitbort
+2  A: 

Here is the sample code to run your application as admin.

ProcessStartInfo proc = new ProcessStartInfo();

            proc.UseShellExecute = true;

            proc.WorkingDirectory = Environment.CurrentDirectory;

            proc.FileName = Application.ExecutablePath;

          proc.Verb = "runas";



            try

            {

                Process.Start(proc);

            }

            catch

            {

                // The user refused the elevation.

                // Do nothing and return directly ...

                return;

            }

            Application.Exit();  // Quit itself

Set the ProcessStartInfo.Verb to “runas” will let it run as admin. Here is related FAQ

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/28f84724-af3e-4fa1-bd86-b0d1499eaefa#x_FAQAnswer91

Sandeep
I think OP is asking for how to force his application to always under with admin priv's not how to run any application from within a c# app as administrator
Rune FS
A: 

It needs the Manifest file. Just place a manifest file and choose AsInvoker or AsAdministrator.

If you can access process you might use proc.Verb = "runas";

Check this : http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/db6647a3-85ca-4dc4-b661-fbbd36bd561f

abhishek