无法使用VS 2015以实用方式打开Visual Studio命令提示符

时间:2017-06-06 08:39:41

标签: c# cmd

我想以编程方式运行visual studios命令。我已经尝试了上面的代码但没有帮助。我得到的是一个命令提示符,我的项目目录打开。

我使用了Execute(" VS140COMNTOOLS")作为输入。

 private void Execute(string vsEnvVar) {

        var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);

        if (Directory.Exists(vsInstallPath)) {
            var filePath = vsInstallPath + "vsvars32.bat";
            if (File.Exists(filePath)) {
                //start vs command process
                Process proc = new Process();

                var command = Environment.GetEnvironmentVariable("ComSpec");
                command = @"" + command + @"";

                //var batfile = @"E:\Test\vstest.bat";
                var args = string.Format("/S/K \" \"{0}\" \"", filePath);

                proc.StartInfo.FileName = command;
                proc.StartInfo.Arguments = args;

                //proc.StartInfo.RedirectStandardInput = true;
                //proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.UseShellExecute = false;

                proc.Start();
            } else {
                Console.WriteLine("File Does not exists " + filePath);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

private Process Execute(string vsEnvVar)
    {
        Process process = new Process();
        ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");//assume location is in path. Otherwise use ComSpec env variable
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo = psi;
        // attach output events 
        process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
        process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
        process.StartInfo = psi;
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();
        process.StandardInput.WriteLine(string.Format("call \"%{0}%vsvars32.bat\""), vsEnvVar);
        process.StandardInput.Flush();
        return process;
    }

现在您可以通过写入process.StandardInput

来执行任何命令
process.StandardInput.WriteLine(@"msbuild c:\MySolution.sln /t:Clean");