-1

I have .bat script in VisualStudio and I call them in C# code. Here is a script and my C# code where I call script. How I can write directly .bat script in my C# code in Process?

//bat script
set SERVICENAME=%1%
arbstate -t %SERVICENAME%

//C# code
Process process = new Process();
process.StartInfo.FileName = "Scripts\\CheckServiceState.bat";
process.StartInfo.Arguments = serviceName;
Dragan
  • 1
  • 2
  • _"How I can write directly .bat script in my C# code"_ - Not sure exactly what you mean but you can create a script in code and use `File.WriteAllLines(batchFileName, script)` to write it out – stuartd Dec 05 '18 at 10:38
  • Why would a programmer, who is competent, ask this. Maybe you should ask how do I do what a user program does. – CatCat Dec 05 '18 at 10:41
  • Are you trying to write a C#/batch hybrid script where if you run the file as C# it runs the C# section and if you run it as batch it runs the batch section? – SomethingDark Dec 05 '18 at 10:47
  • Possible duplicate: https://stackoverflow.com/questions/14020109/why-does-process-startcmd-exe-process-not-work – Klaus Gütter Dec 05 '18 at 10:49
  • A .BAT script/file is a _file_! If you ask how to create a file in C#, then see @stuartd's comment above. If you want to execute Batch code from a C# program _without creating a file_, then see [this answer](https://stackoverflow.com/questions/13320578/how-to-run-batch-script-without-using-bat-extension/13337597#13337597) (execute `cmd.exe` with its input redirected) – Aacini Dec 05 '18 at 14:11

2 Answers2

0

BAT file are interpreted by the command shell cmd.exe. So you have to start cmd.exe and pass the path to the BAT file as parameter. See here for an example and background information: Why does Process.Start("cmd.exe", process); not work?

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • _"So you have to start cmd.exe and pass the path to the BAT file as parameter"_ Not so. From C# you can just use `Process.Start(batchFileName)` – stuartd Dec 05 '18 at 11:04
  • @stuartd: thanks, didn't know that. I always did it the "cmd.exe /c" way. – Klaus Gütter Dec 05 '18 at 12:00
0

You can either do it this way which will be more useful Write the logic in the exe file and then you can argument this exe of your .net code to the bat file To the exe file you can work on the same with arguments by impersonating like go in solution - Properties - Debug- Start Options and then give value something like "/arg " And read these values in your .net and use the same This .bat script you can then also use it in scheduling in the Scheduling manager like Control M etc Hope this helps!