atulya
atulya

Reputation: 539

Open Visual Studio command prompt from C# code

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

Upvotes: 0

Views: 2880

Answers (1)

Ben
Ben

Reputation: 35613

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" "

Upvotes: 1

Related Questions