【问题标题】:Running BAT file as Administrator in Visual Studio 2010 Console App在 Visual Studio 2010 控制台应用程序中以管理员身份运行 BAT 文件
【发布时间】:2012-10-03 08:07:31
【问题描述】:

我想以管理员身份在我的 VS 项目中运行一个 bat 文件。 bat 文件中有一些命令,我​​想执行该文件。这些命令需要管理员权限。代码如下。

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;

    }

所以请告诉我如何运行这些命令或以管理员模式运行此文件。任何类型的帮助将不胜感激。提前致谢 问候

【问题讨论】:

标签: c# android .net console-application elevated-privileges


【解决方案1】:

你有几个选择

您可以指定管理员凭据来启动批处理文件

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();

或者您可以在您的应用上提示输入 UAC,这意味着它启动的任何东西都将以相同的权限运行。

请参阅here,了解如何创建清单文件来执行此操作。

【讨论】:

    【解决方案2】:

    既然你不能跳过UAC,我想你可以在这里得到答案:http://www.vistaclues.com/run-a-batch-file-as-an-administrator/

    只需创建一个快捷方式,将其设置为以管理员身份运行,然后执行它而不是直接调用您的 .BAT 文件。

    【讨论】:

      猜你喜欢
      • 2011-12-29
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 2013-12-22
      • 2013-03-01
      相关资源
      最近更新 更多