2

I want to run several commands via C# application like

Previously I had a batch file and I ran it using C# but now few of the commands can take inputs. But how to do that ?

I tried

 Process cmdprocess = new Process();
        ProcessStartInfo startinfo = new ProcessStartInfo();
        Environment.SetEnvironmentVariable("filename", FileName);
        startinfo.FileName = @"C:\Users\cnandy\Desktop\St\2nd Sep\New_CN\New folder\Encrypt web.config_RSAWebFarm\Decrypt Connection String.bat";

        startinfo.WindowStyle = ProcessWindowStyle.Hidden;
        startinfo.CreateNoWindow = true;
        startinfo.RedirectStandardInput = true;
        startinfo.RedirectStandardOutput = true;
        startinfo.UseShellExecute = false;
        cmdprocess.StartInfo = startinfo;
        cmdprocess.Start();

And in the batch file

cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

aspnet_regiis -pi "CustomKeys2" "C:\Users\cnandy\Desktop\Encryption_keys\CustomEncryptionKeys.xml"

aspnet_regiis -pa "CustomKeys2" "NT AUTHORITY\NETWORK SERVICE"

aspnet_regiis -pdf "connectionStrings" %filename%

But effectively they did not run get executed at all. How to achieve the same where for the last command I can accept an input instead of hard coding

"C:\Users\cnandy\Desktop\Test\Websites\AccountDeduplicationWeb"

?

StrugglingCoder
  • 4,781
  • 16
  • 69
  • 103
  • Possible duplicate of: http://stackoverflow.com/questions/437419/execute-multiple-command-lines-with-the-same-process-using-net – Kaitlyn Sep 03 '15 at 13:57
  • The command parameters may not be correct. Try && instead of single &. Also, consider PowerShell as an alternative. – Ryan Sep 03 '15 at 13:59
  • It should be mentioned that you don't really require all those extra back-slashes, if you added a "@" before the string itself, like for example: @"commands here C:\Test" – Kaitlyn Sep 03 '15 at 14:14

3 Answers3

4

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.

Kaitlyn
  • 791
  • 1
  • 10
  • 28
  • Thanks but 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); these lines throw me compile time errors saying unrecognized escape sequence. – StrugglingCoder Sep 03 '15 at 14:19
  • That would be due to the back-slashes, you could try to use your original formatting of your commands that you wanted to pass instead of using the "@" method. – Kaitlyn Sep 03 '15 at 14:20
  • @user3655102 Updated my answer so it uses back-slashes properly, thus avoiding that issue. – Kaitlyn Sep 03 '15 at 14:24
  • I tried but the commands did not get executed properly . :( But when I put these commands in batch file they work like charm . 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\""); ...... Is there anything that can be done ? – StrugglingCoder Sep 03 '15 at 14:30
  • @user3655102 I would think it's most likely how the commands are being formatted perhaps, I can't try your commands myself personally, but I do know that the other parts of the code in the second method will work fine, excluding the commands used. Here's an example I am using myself: http://i.imgur.com/E4pzdcp.png – Kaitlyn Sep 03 '15 at 14:32
  • Seriously You helped a lot :) Thanks for your help . Figured out the missing backslash error . – StrugglingCoder Sep 03 '15 at 14:40
  • @user3655102 Great to know I managed to help you :) I myself had also encountered the unrecognized escape sequences in the past, due to either missing backslashes, or using them in the wrong places. – Kaitlyn Sep 03 '15 at 14:41
1

Start the batch file using Process object. You can use Environment variables to pass the values between processes. in this case, from C# to bat file you can pass values using environment variable.

c#

Environment.SetEnvironmentVariable("searchString","*.txt")

in bat file you can access the value as like below

dir %searchString%

To start the bat file from c#

System.Diagnostics.Process.Start("path\commands.bat");

Sample code to start notepad from C# with Batch file and Variables

System.Environment.SetEnvironmentVariable("fileName", "test.txt");
System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/commands.bat");
Console.ReadLine();

Bat file

@echo "staring note pad"
notepad %fileName%
CreativeManix
  • 2,162
  • 1
  • 17
  • 29
1

You can still make a batch file as you used to. Only change it needs is accepting variables.

Something like

 CallYourBatch.bat "MyFileName"

Then in you batch file, you can accept a parameter

SET fileName=%~1
aspnet_regiis -pdf "connectionStrings" %fileName%

Similarly the same functionality can be used while forming your command text, if you must do it as part of C# code.

Also might i suggest using a CALL command to call your batch files? More information on the same is at http://ss64.com/nt/call.html

touchofevil
  • 595
  • 4
  • 21