C# – Granting administrator privileges to an application launched at startup without UAC prompt

cnetuacwindows

Background

I've written a small C#/.NET 4.0 application that syncs various settings from a game installed in Program Files to and from other copies of the same game on different machines (think Chrome bookmark sync, but for this game). The sync itself is a relatively simple affair, dealing with files stored inside the game's Program Files folder.

On my machine, this works fine without having to elevate my application through UAC. Windows 7 makes the game use Program Files virtualisation and my application works fine with that.

However, on a lot of tester's machines, I'm getting reports that the application either can't work with the files and in come cases can't even see the game's folder! Having the user right-click and "Run as Administrator" solves the problem in every case.

So, we just set the application's manifest to require admin privileges, right? That's fine (although not ideal) for when the user manually invokes the application or the sync process because they'll be interacting with the application and ready to accept a UAC request.

However, one of the features of my application is a "Sync Automatically" option, which allows the user to "set and forget" the application. With this set, the application puts itself into the registry at HKCU\Software\Microsoft\Windows\CurrentVersion\Run to be run at startup and sits in the system tray syncing the settings in the background as needed.

Obviously, I need to be smarter here. Presenting a UAC prompt as soon as the user logs in to their account or at random intervals afterwards isn't the way forwards.

So, my question!

What's the best way to approach a situation where I'd need to run an application at startup that needs administrator privileges? Is there a way to have the user authorise an installation that causes the system to automatically run the application with the correct privileges without a prompt at startup/login?

Update Just to be clear, this must be achievable in code.

Best Answer

You should consider making your Sync functionality exist within a Windows Service. This is the preferred method for running 'background' functionality on Windows.

The Service can either run under the user's account (assuming they have permissions to modify the files), or you can use another account which does. Worst case, you can run as SYSTEM (although, this isn't best practice).

If you've already got your background process functionality working, then this should be a simple process to convert over to a Service.

There's a sample project here that will set you on the right path: http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx