简体   繁体   中英

C# Directory.GetDirectories - how to workaround UnauthorizedAccessException?

When I try to access a system volume using Directory.GetDirectories(systemVolumePath) my app throws an UnauthorizedAccessException. Fine. I've seen all the answers on here that use try catch - this is not what I'm after.

How can I run my application under an account that does have sufficient permissions to access all folders?

Thanks

I have successfully used the runas.exe tool to do this.

runas.exe /savecred /user:yourusernamehere my_app_that_needs_permissions.exe

This will run the application in the current desktop environment, but with the other user's profile and permissions, so file access (including creating files) will happen with that users credentials.

An interesting sideeffect of this is any files created by your application will be created as the other user as the owner, and your current user may not have the required permissions to access them.

Its a fun little jaunt down the world multi-user environments.

If you are after a way to do this from your own code, these SO posts seem to cover it:

Launch a process under another user's credentials

Using Process.Start() to start a process as a different user from within a Windows Service

As far as I know, you can't 'workaround' the security. What you can do, is require permissions.

You must require elevation from the user, to allow your code to run with the required permissions.

In .NET you can do this using Declarative Syntax , or Imperative Syntax .

Here is a example from Microsoft with imperative syntax to require permission to a single folder:

FileIOPermission permFileIO =
new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\Temp");
try 
{
    // Demand the permission to access the C:\Temp folder.
    permFileIO.Demand();
    resultText.Append("The demand for permission to access the C:\\Temp folder succeeded.\n\n");
}
catch (SecurityException se)
{
    resultText.Append("The demand for permission to access the C:\\Temp folder failed.\nException message: ");
    resultText.Append(se.Message);
    resultText.Append("\n\n");
}

To access those directories you need to be running under the LocalSystem account which isn't something you should consider lightly.

PSExec will help you achieve what you need if it's appropriate to your usage scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM