c# - 在 Visual Studio 2010 控制台应用程序中以管理员身份运行 BAT 文件

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

我想以管理员身份在我的 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;

    }

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

最佳答案

你有几个选择

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

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关于如何创建 list 文件来执行此操作。

关于c# - 在 Visual Studio 2010 控制台应用程序中以管理员身份运行 BAT 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12704332/

相关文章:

c# - 按下取消键 (CTRL+C) 时控制台中的 Topshelf 强制停止服务

.NET:是否可以在安装 .NET 4.0 后安装 .NET frameworks 2.0 和 3.5?

c# - 自动调整 Windows 窗体控件的大小

c# - 在数据绑定(bind)表达式中调用具有 void 返回类型的方法

c# - 从子类提供抽象类成员变量

C# 列表泛型扩展方法与非泛型

c# - 如何获取 Windows 8 Live ID

android - 如何在android中显示一个人的当前年龄(25岁11个月20天)?

java - Android 如何在 "Force Stop"应用程序之后获取最后一个焦点 Activity

android - Eclipse 不编译额外的 jar 文件