…meie igapäevast IT’d anna meile igapäev…

2011-01-25

How to force .NET application to run as an administrator on Windows 7/Vista

UAC

I am making a small utility that modifies registry, hopefully to be released within a few days, more about it then. However, this was the first time I was making a such app under Windows 7 – and I ran into some unexpected difficulties.

When I was trying to delete a registry subkey, I got an invalid access exception. I wasn’t sure what was the reason – I opened the RegistryKey with RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl – which means it should have worked fine… and it would have worked fine on Windows XP, if the user was logged in as an administrator.

But I did not account for User Access Control. You see, administrators for Windows 7 really aren’t running in administrative rights – they are some kind of bastardly combination of a regular user and an administrator. When an application needs to run in administrative rights, Windows pops up UAC dialog asking if you want to allow the program to make changes to your computer.

So I needed to force an application to to require administrative rights, so the Windows 7 would pop up the dialog. But how?

As it came out, you need to add a manifest to your .NET application. Right-click in Visual Studio project, Add file – and add Application Manifest file, usually named app.manifest. Find line:

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

and replace “asInvoker” with “requireAdministrator”:

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

And that’s it. Now Windows 7 will pop up the User Access Control window if you run your application. Read more about app.manifest on Windows Vista and Windows 7 here.

To force user to have administrative rights with Windows XP and older, you should add to your initialization the following tidbit:

if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))

    {

    MessageBox.Show(

        "You must have administrative rights to use this program!\r\n\r\nThe program will now exit.", 

        "Error: no administative rights",MessageBoxButtons.OK, MessageBoxIcon.Hand);

    Environment.Exit(1);

    }

However, I still had some issues with Windows 7 after forcing the application to run in the administrative rights. For example, RegistryKey.DeleteSubKeyTree() method still gave me UnauthorizedAccessException, while RegistryKey.DeleteSubKey() worked just fine – so I had to write my own recursive method to delete subkeytree. Additionally, I was unable to delete a file in Windows folder – “You need a permission from TrustedInstaller to make changes to this file”. Read about manually deleting such files here.

Lisa kommentaar »

Kommentaare veel pole.

RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Blog at WordPress.com.