C#执行cmd命令

时间:2014-12-03 11:42:21

标签: c#

我试图通过c#执行cmd命令,一切正常。 我怎样才能执行" runas" cmd包括密码,或者至少我如何打开cmd提示插入密码。我的代码执行效果很好,这是我似乎无法解决的唯一问题。 我甚至用回声试过但它似乎没有用。

private void btnStart_Click(object sender, EventArgs e)
{

    txtResult.Text = string.Empty;
    if (txtExecutable.Text.Trim() != string.Empty)
    {
        StreamReader outputReader = null;
        StreamReader errorReader = null;
        try
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.CreateNoWindow = true;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = @"/C echo " + txtpass.Text + " | runas /user:" + utente.Text + " wmic.exe /node:" + txtExecutable.Text + " ComputerSystem Get UserName && tasklist /s " + txtExecutable.Text + @" /fi ""imagename eq EmpirumRCHost.exe"" && msinfo32.exe \\" + txtParameter.Text;
            startInfo.ErrorDialog = false;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            process.StartInfo = startInfo;
            process.Start();

            bool processStarted = process.Start();
            if (processStarted)
            {
                //Get the output stream
                outputReader = process.StandardOutput;
                errorReader = process.StandardError;
                process.WaitForExit();

                //Display the result
                string displayText = "Output" + Environment.NewLine + "==============" + Environment.NewLine;
                displayText += outputReader.ReadToEnd();
                displayText += Environment.NewLine + "Error" + Environment.NewLine + "==============" +
                               Environment.NewLine;
                displayText += errorReader.ReadToEnd();
                txtResult.Text = displayText;
            }
        }
        finally
        {
            if (outputReader != null)
            {
                outputReader.Close();
            }
            if (errorReader != null)
            {
                errorReader.Close();
            }
            btnStart.Enabled = true;
        }
    }
}

我需要以远程PC上具有管理权限的域用户身份运行runas命令。

2 个答案:

答案 0 :(得分:0)

您可以尝试添加应用程序清单文件作为讨论here

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

答案 1 :(得分:0)

这就是你必须从C#

运行shell命令
string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);