5

I am trying to write to a file that my local user account does not have access to, how can I open and write to the file as an administrator?

tshepang
  • 12,111
  • 21
  • 91
  • 136

3 Answers3

4

You need to launch another process that has admin rights. To do that call ShellExecute with 'runas' as the second parameter (this will open a User Account Control dialog). That executable may be separate or may be the same one that is calling ShellExecute.

Isso
  • 1,285
  • 11
  • 23
1

A good wrapper class for impersonation in a using block is what I have used with success before:

using (new Impersonation(domain, username, password))
{
   // <code that executes under different user context>
}

The Using statement is great for code readability as seen in this example and to ensure that the object used is properly disposed when the final } character is reached (running out of scope). Apparently there is no guarantee of garbage collection though (see first answer).

Two different sources for such a wrapper class:

  1. This stackoverflow solution features good readability and usability.

  2. Here is similar code from CodeProject: A small C# Class for impersonating a User.

See MSDN for more on the Using statement.

Community
  • 1
  • 1
Stein Åsmul
  • 39,960
  • 25
  • 91
  • 164
  • That's really cool. I suppose it could be compiled into a .dll and referenced. – RubberDuck Jun 02 '14 at 20:55
  • I haven't tried this particular code, but similar code, but yes you can wrap it in a dll to the best of my knowledge (always new restrictions in newer versions of .NET though). – Stein Åsmul Jun 02 '14 at 21:02
  • What I am referring to with .NET and Windows restrictions is Code Access Security, Windows Security, Digital certificates and similar constructs. As far as I know impersonation should work despite these security measures, but that cannot be guaranteed for the future. – Stein Åsmul Jun 09 '14 at 17:07
1

You might want to look at PSEXEC from Microsoft, it allows you to execute files in elevated mode, and as a different user if desired.

You didn't say how the file is opened for writing, but PSEXEC can be used in conjunction in batch/vbs file to execute another batch/vbs/exe.

PatricK
  • 6,375
  • 1
  • 21
  • 25
  • **psexec** is a great tool, but more suited for system administration than to be run from code in my opinion. You get better exception handling with code, less clunky deployment and overall better security. – Stein Åsmul Jun 08 '14 at 18:17