3

My scenario in C# project is user will pass path like "c:\homedir\mydir" to batch file then batch file should accept this path and create directory at the specified path.

I don't know how to pass string to batch file through c# and how batch file will accept string and process it.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rushikesh
  • 529
  • 4
  • 18
  • 43
  • [How to send series of commands to a command window process?](http://stackoverflow.com/a/4789324/417747) – NSGaga-mostly-inactive Apr 01 '13 at 13:18
  • Why pass parameter to batch file ? You can't process inside C# app ? It complicates things like getting feedback from batch file. How will you know if something went wrong ? You can use status/result codes but that is not very robust. – pero Apr 01 '13 at 13:19
  • Hi Peter Thanks for your suggestions, I will try to do the same from c# application. – Rushikesh Apr 02 '13 at 06:07

2 Answers2

2

Create a process and pass your argument(s) through the StartInfo.Arguments property.

Process proc = new Process();
proc.StartInfo.FileName = //path to your BAT file
proc.StartInfo.Arguments = String.Format("{0}", @"C:\homedir\mydir");
//set the rest of the process settings
proc.Start();

That will load your BAT file and pass whichever arguments you've added. Your BAT file can access the arguments using %1 for the first argument, %2 for the second one etc...

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • Maybe add some info how will C# code know that batch process ended. What to do if it loops indefinitely ? BTW, before even start new process check if given dir exists. – pero Apr 01 '13 at 13:23
  • Fair comment but my answer assumes OP will take some responsibility with error handling. There aren't enough details in OP's post to make it worth trying to cover all possible aspects. – keyboardP Apr 01 '13 at 14:09
1

Since you didn't gave us any information, I just give an example of these subjects.

First of all, you need to use Process class include System.Diagnostics namespace.

Provides access to local and remote processes and enables you to start and stop local system processes.

An example with a batch file:

 Process p = new Process();
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "yourbatchfile.bat";
 p.Start();

For passing arguments, you can use ProcessStartInfo.Arguments property.

Gets or sets the set of command-line arguments to use when starting the application.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364