C#以管理员身份运行CMD
我试图以管理员身份运行cmd命令。但CMD窗口意外关闭。如果CMD窗口停留,我可以看到错误。我试图使用process.WaitForExit();
C#以管理员身份运行CMD
我试图以管理员身份运行代码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窗口保持运行/显示?
捕获从流程的输出(S):
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();
然后做与输出的东西。
注意:您不应该尝试同时读取两个流,因为存在死锁问题。您可以为其中的一个或两个添加异步阅读,或者只是来回切换,直到完成故障排除。
您正在从runas.exe
可执行文件开始进程。这不是如何提升流程。
相反,您需要使用shell执行来启动您的可执行文件,但使用runas
动词。沿着这些线路:
ProcessStartInfo psi = new ProcessStartInfo(...); // your command here
psi.UseShellExecute = true;
psi.Verb = "runas";
Process.Start(psi);
你为什么要传递三个问题点作为ProcessStartInfo()的构造参数?对不起,我是C#的初学者。 – Isuru
这是给你填写你的命令,我专注于提升并假设你知道你想运行什么。 “cmd.exe”代替'...' –
加上psi.Verb =“runas”;然后变成管理员?或者什么可执行属性来设置? –
下面的方法确实有效...
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();
}
这是最有可能造成所有这些以及与string.replace'“'和\ –