Calling external scripts from C#
Posted: (EET/GMT+2)
If you need to run a script written in another programming language from a .NET application, the usual
approach is to start it as an external process. That said, the System.Diagnostics.Process class works the same way regardless of the script language: Python, JavaScript, etc.. Only the executable and arguments change.
This is the basic pattern:
using System.Diagnostics; ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "command"; psi.Arguments = "arguments"; psi.RedirectStandardOutput = true; psi.UseShellExecute = false; Process process = Process.Start(psi); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit();
From there, you just replace the command and arguments for the script you want to run.
For example, this is how you'd run a PowerShell script:
psi.FileName = "pwsh"; psi.Arguments = "-File script.ps1";
Then, a classic Windows batch file (.bat, .cmd):
psi.FileName = "cmd.exe"; psi.Arguments = "/c script.bat";
And a Python script:
psi.FileName = "python"; psi.Arguments = "script.py";
Finally, a Node.js (JavaScript) script:
psi.FileName = "node"; psi.Arguments = "script.js";
In all cases, the interpreter or shell must be available in the system path. You can also provide full paths to the executables if needed. This approach works for quick automation tasks, legacy scripts, or integrating tools that don’t have native .NET libraries.
Hope this helps!