Search Unity

Running Batch File From C# Script

Discussion in 'Editor & General Support' started by Goupi, Jul 6, 2015.

  1. Goupi

    Goupi

    Joined:
    May 27, 2015
    Posts:
    9
    Hello! I have a batch file in my assets folder that I want to use with my game and I was wondering how I would run it from a C# script.

    Thanks!
     
  2. greg-harding

    greg-harding

    Joined:
    Apr 11, 2013
    Posts:
    524
    Here's an edited snippet from a wrapper we use. It's part of other stuff that handles threaded and async calls so it's probably longer than you need to just quickly call something (and doesn't define all the variables being used) but it should give you an idea of where to look in the .Net docs to get your stuff done.

    Code (CSharp):
    1. using System.Diagnostics;
    2.  
    3. // ...
    4.  
    5. public void Run() {
    6.     // start the child process
    7.     Process process = new Process();
    8.  
    9.     // redirect the output stream of the child process.
    10.     process.StartInfo.UseShellExecute = false;
    11.     process.StartInfo.RedirectStandardOutput = true;
    12.     process.StartInfo.CreateNoWindow = true;
    13.     process.StartInfo.FileName = command;
    14.     process.StartInfo.Arguments = arguments;
    15.  
    16.     if (!string.IsNullOrEmpty(workingDirectory)) {
    17.         process.StartInfo.WorkingDirectory = workingDirectory;
    18.     } else {
    19.         process.StartInfo.WorkingDirectory = Application.temporaryCachePath; // nb. can only be called on the main thread
    20.     }
    21.  
    22.     int exitCode = -1;
    23.     string output = null;
    24.  
    25.     try {
    26.         process.Start();
    27.  
    28.         // do not wait for the child process to exit before
    29.         // reading to the end of its redirected stream.
    30.         // process.WaitForExit();
    31.  
    32.         // read the output stream first and then wait.
    33.         output = process.StandardOutput.ReadToEnd();
    34.         process.WaitForExit();
    35.     }
    36.     catch (Exception e) {
    37.         Debug.LogError("Run error" + e.ToString()); // or throw new Exception
    38.     }
    39.     finally {
    40.         exitCode = process.ExitCode;
    41.  
    42.         process.Dispose();
    43.         process = null;
    44.     }
    45.  
    46.     // process exitCode/output, call onComplete handlers etc.
    47.     // ...
    48. }
    Or, check stack overflow - plenty of snippets to get you started on there.
    http://stackoverflow.com/questions/5519328/executing-batch-file-in-c-sharp
     
  3. prakyath_unity

    prakyath_unity

    Joined:
    Dec 11, 2020
    Posts:
    9
    Code (CSharp):
    1. Process.Start(Application.streamingAssetsPath + "/FolderName" + "/run.bat");
     
    radiantboy and Hiromichi-Yamada like this.