Check administrator permission while searching for files in C#

2k views Asked by At

I am trying to get path of all EXE files present on my C drive. I am facing an issue which is nothing more than access problem due to lack of administrative rights.

I wrote this code,but the system is denying access to those files.

DriveInfo drive = new DriveInfo(@"C:\\");
foreach (DirectoryInfo dir in drive.RootDirectory.GetDirectories(".*exe",SearchOption.AllDirectories))
{
     path.Add(dir.ToString());                                           
}

How can I get Windows to ask the user to elevate permissions to administrative (the shield/dark screen message)?

3

There are 3 answers

8
devavx On

I am not sure if this is the answer to your question or not,but it seems to suppress the permissions.To make sure your application runs with administrator permission, add a new manifest file from add new item menu.If everything goes correctly you should be seeing a new file named app.manifest in the solution explorer.

When you've done it,open app.manifest from Solution Explorer by double clicking it,when it opens in the code editor replace its trustinfo section with this;

 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
            If you want to change the Windows User Account Control level replace the 
            requestedExecutionLevel node with one of the following.

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

            Specifying requestedExecutionLevel node will disable file and registry virtualization.
            If you want to utilize File and Registry Virtualization for backward 
            compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

What we did is,we changed the application's manifest to make sure it gets administrative right's while running.

This was to illustrate,how to run the application as administrator everytime,but instead if your need is to only check if the application has administrative rights,you can check it in this way;

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal appprincipal = (WindowsPrincipal) Thread.CurrentPrincipal;
if(appprincipal.IsInRole("Administrators"))//Check if the current user is admin.
{
  //Yeah,the app has adminstrative rights,do what you need.
}
else
{
  //Not running as administrator,react as needed.
  //Show error message.
}

Update

To get the full path of current application, use this;

string path=Application.ExecutablePath;

Application.ExecutablePath returns the absolute path of the exceutable which is calling the method.
For Ex : If you application is Notepad,it would return C:\Windows\System32\Notepad.exe.

Hope it solves the issue.

0
Vinod Kumar Y S On

You need to have administrative rights to access root drive. You can use the below code to test if your app has Administrator rights.

    static void Test()
    {
        if (!HasAdministratorRights())
        {
            // throw error to notfying that the app need admin rights
        }

        // Get files for 
    }

    private static bool HasAdministratorRights()
    {
        var currentIdentity = WindowsIdentity.GetCurrent();
        if (currentIdentity == null)
            return false;

        return new WindowsPrincipal(currentIdentity)
            .IsInRole(WindowsBuiltInRole.Administrator);
    }
0
Thilina H On

If you have any account with admin right then you can run that code snippet using impersonation.

Here is the link of implementation