Question

I have a program that works with the file system a lot and need certain methods to run as administrator. I can't have the application it's self run as admin as I need to use drag and drop on the form. I imagine that one method can't be executed with admin rights. I don't really want to make a anther executable for one method. If I do make another executable what's the best way to pass multiple arguments through the application and redirect the output? I hope I worded this correctly and made my self clear.

Était-ce utile?

La solution

You can not run a single method as administrator. However, you can impersonate a user that has administrator rights at the start of the method, execute some code as the other user and then go back to the original user.

The accepted answer to the following question lists some options: How do you do Impersonation in .NET?


In his answer to the above linked question, Matt Johnson also shows some code to do it hassle free, which he obviously also posted as a DLL to GitHub, where you can download and use it.

Autres conseils

Your only options are:

  1. Run the whole program as admin
  2. Re-launch your program as admin when the user wants to do a admin function
  3. Re-think your design approach so your method no longer requires being admin
  4. Use some form of IPC to launch a 2nd app that is elevated and does the requests for you.

For the IPC route, the easiest way I know of is using WCF with named pipes, you just treat the WCF communication like you would any other class in your code and just communicate through normal functions.

If I understand you correctly, you need your program to start in elevated mode. The easiest way to do so, is to specify it as a requirement in the application manifest file.

In order to add a manifest to your app, you can follow these steps:

  1. Right click your project
  2. Add -> New Item -> Application Manifest file
  3. In the new .manifest file, replace <requestedExecutionLevel level="asInvoker" uiAccess="false" /> with <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
  4. Make sure the application is configured to run with your new manifest by going to: Right click your project -> Properties -> Application tab -> Manifest

You can read more about the application manifest here.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top