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"

?

3
  • Possible duplicate of: stackoverflow.com/questions/437419/… Commented Sep 3, 2015 at 13:57
  • The command parameters may not be correct. Try && instead of single &. Also, consider PowerShell as an alternative. Commented Sep 3, 2015 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" Commented Sep 3, 2015 at 14:14

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
@user3655102 Updated my answer so it uses back-slashes properly, thus avoiding that issue.
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 ?
@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: i.imgur.com/E4pzdcp.png
|
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

1 Comment

Thanks .. I modified my question accordingly . But I am still unable to execute them . Could you take a look ?
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%

2 Comments

Thanks .. I modified my question accordingly . But I am still unable to execute them . Could you take a look ?
I have added sample code, which I have been tested and works fine. I dont wanted to run "aspnet_regiis" in my server. so used notepad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.