Execute Multiple Command Lines with the Same Process Using .Net

Execute multiple command prompt commands from c#

You can try:

    Process cmd = new Process();

cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

using (StreamWriter sw = cmd.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("openssl genrsa -aes256 -out E:\\testing_folder\\test_file_com.key.pem 2048");
sw.WriteLine("123456");
sw.WriteLine("123456");
}
}

Execute multiple command lines with the same process using C#

Your question is a little confusing but I think i see your problem. First you should check out this blog post to see common issues with System.Diagnostics.Process. Your code happens to violate one that isn't listed there. The reuse of the Process object itself.

You need to refactor the code like:

    class MyProcessStarter
{
private ProcessStartInfo _startInfo = new ProcessStartInfo();
public MyProcessStarter(string exe, string workingDir)
{
_startInfo.WorkingDirectory = workingDir;
_startInfo.FileName = exe;
_startInfo.UseShellExecute = false;
_startInfo.RedirectStandardOutput = true;
}

public string Run(string arguments)
{
_startInfo.Arguments = arguments;
Process p = Process.Start(_startInfo);
p.Start();
string strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return strOutput;
}
}

I've written a more complete and accurate implementation called ProcessRunner. The following demonstrates it's usage to perform the same operation:

using CSharpTest.Net.Processes;
partial class Program
{
static int Main(string[] args)
{

ProcessRunner run = new ProcessRunner("svn.exe");
run.OutputReceived += new ProcessOutputEventHandler(run_OutputReceived);
return run.Run("update", "C:\\MyProject");
}

static void run_OutputReceived(object sender, ProcessOutputEventArgs args)
{
Console.WriteLine("{0}: {1}", args.Error ? "Error" : "Output", args.Data);
}
}

Execute multiple CMD commands in same process (window) without showing separate windows

You are running the process for each 'file' in 'files'. Therefore if you have 100 files, it will result in 100 command windows.

If you're not interested in the output contained within those command windows (and as you're outputting the results to a text file, I'll presume not), you can just hide them with all with p.StartInfo.CreateNoWindow = true;.

c# open cmd.exe process and Execute multiple commands

There three things you can do to achieve what you want. The easiest is to set the working directory of the process through ProcessStartInfo. This way you will only have to execute the command to start the VPN client.

The second option is redirecting the input and output of the process. (Also done through the ProcessStartInfo) This is something you want to do if you need to send more input to the process, or when you want to retrieve the output of the process you just started.

The third option is to combine the two commands with the & symbol. Using the & symbol makes cmd.exe execute the two commands sequentially (See here for an overview of the available symbols). Using this option will result in a command like this: /c cd path & vpnclient.

However because you just want to change the working directory of the process using the first option makes your code more readable. Because people reading your code do not need to know the & symbol in bash to understand what your code does. Changing the working directoy is done with the WorkingDirectory (MSDN) property of ProcessStartInfo (MSDN). See the following code:

var processInfo = new ProcessStartInfo("cmd.exe", @"/c vpnclient connect user validuser pwd validpassword nocertpwd validconnectionentry ");
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = path;

Running multiple commands from C# application

Try this:

Process p = new Process()  
{
StartInfo = new ProcessStartInfo("cmd.exe")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};

p.Start();

using (StreamWriter sw = p.StandardInput)
{
sw.WriteLine("First command here");
sw.WriteLine("Second command here");
}

p.StandardInput.WriteLine("exit");

Alternatively, try this more direct way (which also implements the last thing you requested):

string strEntry = ""; // Let the user assign to this string, for example like "C:\Users\cnandy\Desktop\Test\Websites\AccountDeduplicationWeb"

Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd.exe")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};

p.Start();

p.StandardInput.WriteLine("cd C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319");
p.StandardInput.WriteLine("aspnet_regiis -pi \"CustomKeys2\" \"C:\\Users\\cnandy\\Desktop\\Encryption_keys\\CustomEncryptionKeys.xml\"");
p.StandardInput.WriteLine("aspnet_regiis -pa \"CustomKeys2\" \"NT AUTHORITY\\NETWORK SERVICE\"");
p.StandardInput.WriteLine("aspnet_regiis -pdf \"connectionStrings\" " + strEntry);

p.StandardInput.WriteLine("exit"); //or even p.Close();

If using the second way, it is recommended to let the user enter the path in a textbox, then grab the string from the textbox's Text property, where all the necessary extra back-slashes will be automatically appended.

It should be mentioned that no cmd will show up running your batch file, or the commands.

How to execute multiple commands to open application in Process.Start() that opens cmd.exe in single process using command-line?

Thanks to @Babbillumpa i've solved my problem:

Dim _processStartInfo As ProcessStartInfo = New ProcessStartInfo()
_processStartInfo.WorkingDirectory = appPath
_processStartInfo.FileName = "cmd.exe"
_processStartInfo.Arguments = "/k app.exe"
_processStartInfo.CreateNoWindow = True

Dim myProcess As Process = Process.Start(_processStartInfo)
'wait for specific time for the thread to be closed
myProcess.WaitForExit(500)

' Close process by sending a close message to its main window.
myProcess.CloseMainWindow()
' Free resources associated with process.
myProcess.Close()


Related Topics



Leave a reply



Submit