Nikhil H Kuren
Nikhil H Kuren

Reputation: 31

How to give administrator rights to code in C#

I am working on a project called computer scanner, But when I run my code in order to scan my hard drives its gives me an exception "Access Denied to System Volume Information Folders" and there are some other folders too which has the same behavior I cannot access them.

After studying about this Exception from Internet I have got to learn that after adding "Manifest File" and changing it option to "Require Administrator" to the program will run as a ADMINISTRATOR but unfortunately nothing as such happened. I am using some code which would allow me to run my code as a Administrator, but still showing me the same exception.

WindowsIdentity CurrentIdentity = WindowsIdentity.GetCurrent();
                WindowsPrincipal CurrentPrincipal = new      WindowsPrincipal(CurrentIdentity);

                if (CurrentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
//Scanning Code will Execute
}

Upvotes: 3

Views: 14132

Answers (2)

Tahir Rehman
Tahir Rehman

Reputation: 332

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.

Upvotes: 4

Nahum
Nahum

Reputation: 7197

You CANNOT give yourself admin privileges in code at all, that would be ridiculous! You must run visual studio as admin by RightClick->run as admin and your final application must be ran as admin as well.

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

in order to force the user to run as admin.

This won't make the application to work as admin but will promote user so that the application asks the user to run as admin during application launch

Upvotes: 4

Related Questions