Open Visual Studio command prompt from C# code

断了今生、忘了曾经 提交于 2019-12-25 08:53:38

问题


I am trying to open Visual studio Command prompt using C# code.

Here is my code

private void Execute(string vsEnvVar)
{

 var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);

 // vsEnvVar can be VS100COMNTOOLS, VS120COMNTOOLS, VS140COMNTOOLS

 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("/K  \"{0}\" \"{1}\"" ,filePath, batfile);  

        proc.StartInfo.FileName = command;
        proc.StartInfo.Arguments = args;
        proc.StartInfo.CreateNoWindow = false;
        proc.StartInfo.UseShellExecute = false;  

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

But the args string is not getting properly formatted. I am getting below formatted string

"/K  \"C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\vsvars32.bat\" \"E:\\Test\\vstest.bat\""    

extra "\" is getting added.

Please point out what I am missing. Thanks


回答1:


The string is being formatted as you asked, but you have asked for the wrong thing. "E:\Test\VStest.bat" is being passed as an argument to VCVars.bat, but I suspect you want it to be executed after it.

Try this:

var args = string.Format("/S/K \" \"{0}\" && \"{1}\" \"" ,filePath, batFile);

This should produce:

"/S/K \" \"C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\Tools\\vsvars32.bat\" && \"E:\\Test\\vstest.bat\" \" \"

Which as a string is:

/S/K " "C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat" && "E:\Test\vstest.bat" "


来源:https://stackoverflow.com/questions/34945164/open-visual-studio-command-prompt-from-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!