2

I am currently faced with a problem, I need to execute a batch script within a programs memory (so it does not have to extract the batch file to a temporary location).

I am open to solutions in C# and C++

Any help would be appreciated

Peter
  • 33
  • 1
  • 3

4 Answers4

5

cmd.exe won't run a script from the memory of your process. The options which seem most obvious to me are:

  1. Relax the constraint that stops you extracting the script to a temporary file.
  2. Compress your script into a single line and use cmd.exe /C to execute it. You'll need to use the command separator &&.
  3. Write your own batch command interpreter.
  4. Use a different scripting language.

Options 3 and 4 aren't really very attractive! Option 1 looks pretty good to me but I don't know what's leading to your constraint.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Regarding option 2: the length of the command line is limited: http://stackoverflow.com/q/3205027/402322 – ceving Aug 09 '16 at 20:59
3

In C# it's an easy way to use System.Diagnostics for the job. How!?

Basically, every batch command is an .exe file so you can start it in a separate process.

Some code:

        using System.Diagnostics;
        static void Main()
        {
           Process batch;

           batch = Process.Start("ping.exe", "localhost");
           batch.WaitForExit();
           batch.Close();

           batch = Process.Start("choice.exe", "");
           batch.WaitForExit();
           batch.Close();

           batch = Process.Start("ping.exe", "localhost -n 10");
           batch.WaitForExit();
           batch.Close();
      }

If you don't want to start every command in a separate process the solution is with a simple stream redirection.

      ProcessStartInfo startInfo = new ProcessStartInfo();
           startInfo.FileName = @"cmd.exe"; // Specify exe name.
           startInfo.UseShellExecute = false;
           startInfo.ErrorDialog = false;
           startInfo.RedirectStandardInput = true;

           //
           // Start the process.
           //
           Process process = Process.Start(startInfo);


           string[] batchFile = {"ping localhost",  "ping google.com -n 10", "exit"};

           int cmdIndex = 0;

           while (!process.HasExited) 
           {
               if (process.Threads.Count == 1 && cmdIndex < batchFile.Length)
               {
                   process.StandardInput.WriteLine(batchFile[cmdIndex++]);
               }
           }
Nikolay
  • 1,076
  • 1
  • 13
  • 11
3

Open a pipe to the command shell and write the program code into that pipe. Here is an example: http://support.microsoft.com/default.aspx?scid=kb;en-us;190351

ceving
  • 21,900
  • 13
  • 104
  • 178
1

What's a good way to write batch scripts in C#?

Community
  • 1
  • 1
tugberk
  • 57,477
  • 67
  • 243
  • 335