1

I want to run a bat file in my VS project as administrator. There are some commands in the bat file and i want to execute that file. Those commands need administrator privileges. The code is given under.

AndroidSmS aHelper = new AndroidSmS();
string renameMsg = aHelper.RenameFile();

public string RenameFile() {

        string renameBATPath = ConfigurationManager.AppSettings["RenameBATPath"].ToString();
        string o;
        string str = DateTime.Now.ToOADate().ToString();
        using (var p = new System.Diagnostics.Process())
        {
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = @renameBATPath;
            p.StartInfo.Arguments = DateTime.Now.ToShortDateString().ToString().Replace('/', '-')+".db";
            p.Start();
            o = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }
        return o;

    }

So can some please tell me how can i run these commands or run this file in administrator mode. Any type of help will be appreciated. Thanks in advance Regards

Tassadaque
  • 8,129
  • 13
  • 57
  • 89
Zeb-ur-Rehman
  • 1,121
  • 2
  • 21
  • 37

2 Answers2

2

You have a couple of options

You could specify the admin credentials to launch the batch file with

p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @renameBATPath;
p.StartInfo.Arguments = DateTime.Now.ToShortDateString().ToString().Replace('/', '-')+".db";
p.StartInfo.UserName = "administrator";
char[] password = { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' };
SecureString adminpassword = new SecureString();
foreach (char c in password)
{
    adminpassword.AppendChar(c);
}
p.StartInfo.Password = adminpassword;
p.Start();

Or you could prompt for UAC on your app which would mean anything that it started would run with the same privileges.

See here on how to create a manifest file to do this.

Bali C
  • 30,582
  • 35
  • 123
  • 152
0

Since you cannot skip the UAC, I think you may get an answer here: http://www.vistaclues.com/run-a-batch-file-as-an-administrator/

Just make a shortcut, set it to be run as administrator, and execute it instead of calling your .BAT file directly.

Veli Gebrev
  • 2,481
  • 4
  • 31
  • 48