Open Visual Studio command prompt from C# code - c#

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

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

Related

This should be so simple, but I can't get it to work

I wrote a simple c# program to automate the process of signing files and I just can't get it to work. Sorry, but I'm no expert in C# (obviously)! Here's my code:
static void Main(string[]
// This progam makes it easy to remember the parameters that need to be passed to signtool and automates the process
if (args.Length < 3)
{
Console.WriteLine("Usage: SignFile FileToSign .pfxfile Password");
}
else
{
try
{
string signTool = "\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\signtool.exe\"";
string fileToSign = args[0];
string pfxFile = args[1];
string password = args[2];
string commandLine = "/C " + signTool + " sign /f \"" + pfxFile + "\" /fd SHA256 /p "
+ password + #" /t http://timestamp.verisign.com/scripts/timestamp.dll " + fileToSign;
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
System.IO.Directory.SetCurrentDirectory(".");
startInfo.Arguments = commandLine;
Process process = new Process();
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
throw;
}
}
}
When I run it I get 'C:\Program' is not recognized as an internal or external command.
I also tried using the short version of the directory name:
string signTool = "\"c:\\PROGRA~2\\MICROS~2\\Windows\\v7.0A\\Bin\\signtool.exe\"";
But this I get:
The filename, directory name, or volume label syntax is incorrect.
I could say more, but I think I'll leave this as simple as it is...
Try it with # in front, like this:
string signTool = #"""C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\signtool.exe""";
The error was fixed by comment 2 on my original question:

C# Running batch file with arguments using UseShellExecute read the content instead executing it

I'm trying to run a batch file with arguments and also redirect the output.
When I don't redirect the output and use UseShellExecute = true, the batch file runs with the arguments as expected.
When I use UseShellExecute = false (to do the redirect), then I see that the command-line opens for a split a second and then closes.
I've read the output, using string output = proc.StandardOutput.ReadToEnd();
and I see that it contains the batch file content...
Can someone help me understand why it happens?
Thank you for your help :)
Here's the relevant code:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = false;
proc.EnableRaisingEvents = false;
// the command
proc.StartInfo.FileName = command;
// the parameters of the command
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
try
{
// in case there is missing '"'
if (isContainQuote && index < 0)
{
str = "missing '\"' in the command " + commandStr;
}
else
{
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
if (bWaitForExit)
{
proc.WaitForExit(m_SHELL_CMD_TIMEOUT);
str = "Succeed to run the command: " + commandStr + ", Output: " + proc.StandardOutput.ReadToEnd();
}
else
{
str = "Succeed to run the command: " + commandStr;
}
}
}
catch (Exception e)
{
str = e.Message + ". Failed to run the command: " + commandStr;
// return the error from the operation system
}
Seeing your batch file could help. By default batch files echo their commands to standard out.
Try adding an #ECHO OFF command to the beginning of the batch file to be sure that the batch file commands aren't echoed to the standard output.

Show cmd commands on C# winform Application

I need to write a small utility to rebuild solution. I am using below code to do the same.
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string cmd1 = #"""C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
cmd1 = "\"" + cmd1 + "\"";
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
using (StreamReader reader = cmd.StandardOutput)
{
string result = reader.ReadToEnd();
listBox1.Items.Add(result);
}
}
If you will observe in command prompt then you can see executions output but same thing is not getting reflected in list box.
Please help to solve this issue.
Thank you in advance.
You can redirect the output to a temporary file and then can read the file like-
string cmd1 = "help > e:/temp.txt"; //e:/temp.txt is temporary file where the output is redirected.
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
//You don't need to read console outputstream
//UseShellExecute = false,
//RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
//Check if file exist or you can wait till the solution builds completely. you can apply your logic to wait here.
if (File.Exists("E:/temp.txt"))
{
//Read the files here
string[] lines = File.ReadAllLines("E:/temp.txt");
//Do your work here
}
}
You can do it async:
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string batFile = #"C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat";
string args = "x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
ProcessStartInfo cmdsi = new ProcessStartInfo(batFile)
{
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true
};
using (Process cmd = new Process())
{
cmd.StartInfo = cmdsi;
cmd.OutputDataReceived += (sender, args) => listBox1.Items.Add(string.IsNullOrEmpty(args.Data) ? string.Empty : args.Data);
cmd.Start();
}

Execute command line using C#

All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.

SharpFFMpeg ffmpeg conversion tutoiral

I am after a good tutorial or how to on using SharpFFMpeg or if there is an easy way to use ffmpeg in c# ...
I would like to convert video.(x format) to video.flv taking screenshots and saving them as i go.
If there is a good tutorial out there or you know an easy way to do please post it here.
Thanks,
Kieran
Thats using ffmpeg.exe whith c# not using sharpffmpeg.
Running command line args
www.codeproject.com/KB/cs/Execute_Command_in_CSharp.aspx
Extracting images
http://stream0.org/2008/02/howto-extract-images-from-a-vi.html
protected void BTN_convert_Click(object sender, EventArgs e) {
String runMe = #"C:\Documents and Settings\Wasabi Digital\My Documents\Visual Studio 2008\Projects\Evo\WEB\Bin\ffmpeg.exe";
String pathToFiles = #"C:\Documents and Settings\Wasabi Digital\My Documents\Visual Studio 2008\Evo\WEB\test\";
String convertVideo = " -i \"" + pathToFiles + "out.wmv\" \"" + pathToFiles + "sample3.flv\" ";
String makeImages = " -i \"" + pathToFiles + "out.wmv\" -r 1 -ss 00:00:01 -t 00:00:15 -f image2 -s 120x96 \"" + pathToFiles + "images%05d.png\"";
this.ExecuteCommandSync(runMe,convertVideo);
this.ExecuteCommandSync(runMe, makeImages);
}
And this is a code snipit taken from the first link. The extra quotation marks around the usage of command let it run with spaces in its name. ie ".../My Documents/..."
public void ExecuteCommandSync(String command, String args) {
try {
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("\""+command+"\"",args);
Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Debug.WriteLine(result);
} catch (Exception objException) {
// Log the exception
}

Categories

Resources