簡體   English   中英

C#以管理員身份運行CMD

[英]C# Run CMD as Administrator

我正在嘗試以管理員身份運行cmd命令。 但是CMD窗口意外關閉。 如果CMD窗口停留,我可以看到錯誤。 我試圖使用process.WaitForExit();

我正在嘗試以管理員身份運行代碼zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

這是我的代碼。

        //The command that we want to run
        string subCommand = zipAlignPath + " -v 4 ";

        //The arguments to the command that we want to run
        string subCommandArgs = apkPath + " release_aligned.apk";

        //I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
        //Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
        string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\""";

        //Run the runas command directly
        ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");

        //Create our arguments
        string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @"""";
        procStartInfo.Arguments = finalArgs;

        //command contains the command to be executed in cmd
        using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
        {
            proc.StartInfo = procStartInfo;
            proc.Start();

        }

有沒有辦法使CMD窗口保持運行/顯示?

您正在從runas.exe可執行文件啟動進程。 那不是提升流程的方法。

相反,您需要使用shell execute來啟動您的可執行文件,但要使用runas動詞。 遵循以下原則:

ProcessStartInfo psi = new ProcessStartInfo(...); // your command here
psi.UseShellExecute = true;
psi.Verb = "runas";
Process.Start(psi);

捕獲過程中的輸出:

proc.StartInfo = procStartInfo;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start()
// string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();

然后對輸出執行一些操作。

注意:由於存在死鎖問題,因此您不應嘗試同時同步讀取兩個流。 您可以為其中之一或兩者添加異步讀取,或者只是來回切換直到完成故障排除。

以下方法實際上有效...

private void runCMDFile()
{
    string path = @"C:\Users\username\Desktop\yourFile.cmd";

    Process proc = new Process();                        

    proc.StartInfo.FileName = path;
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.CreateNoWindow = false;
    proc.StartInfo.RedirectStandardOutput = false;
    proc.StartInfo.Verb = "runas";                         
    proc.Start();
    proc.WaitForExit();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM