0

I have a small C# program to modify a xml file which is located under Program Files. The machine is a Windows 7 machine. This small program is launched by a batch file (called A.bat) because I want to pass a parameter to it.

I have a master batch file (called M.bat) which is the start point. The M.bat will start an installer and wait untile the installation finished. Then the M.bat will start A.bat which will launch my small program with a parameter.

Right now I get the following exception:

System.UnauthorizedAccessException: Access to the path 'C:\Program Files\MyTest\Test.config' is denied.

I know it is caused by tighter security in Win7. It works fine under XP.

I cannot use "Run as Administrator" to start M.bat or manually "Run as Administrator" to start A.bat because both will report cannot find the target executable (because the start location is not really the "current" location then).

Is there a way to start an executable as Administrator in batch file? or in C# program I can give myself Administrator right?

or ...

5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210
  • 3
    I don't really know what you're asking here. Neither an application nor a batch file can elevate its privileges to administrator without the user's permission. You already *know* that's the problem. Wouldn't you be better off trying to fix the bug in your code that's keeping you from using "Run as Administrator", namely not assuming a particular start location? – Cody Gray - on strike Feb 01 '11 at 15:17

3 Answers3

4

Not in a way that is invisible/hidden from the user... I would suggest finding a way to make it work when run as an administrator. Or you could set the application manifest (see this: http://www.enusbaum.com/blog/2007/08/26/how-to-run-your-c-application-as-administrator-in-windows-vista/) to run your app as admin, that might work as well.

Bottom line, you cannot run with admin privileges unless you run as admin, or unless your user switches off UAC (which is not recommended at all).

Gabriel Magana
  • 4,338
  • 24
  • 23
2

You'll need to elevated your privileges through a UAC prompt. Add a manifest to your program as described in this answer.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

You should request for admin privileges at program start up. Look at this sample

Anton Semenov
  • 6,227
  • 5
  • 41
  • 69