Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shell execute a file in C#?

Tags:

c#

.net

I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.

Is it possible?

EDIT:

Sample code:

string pythonScript = @"C:\callme.py";

string workDir = System.IO.Path.GetDirectoryName ( pythonScript );

Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";

I don't get any error, but the script isn't run. When I run the script manually, I see the result.

like image 557
Joan Venge Avatar asked Apr 14 '09 23:04

Joan Venge


2 Answers

Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.

    private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
    {

        ProcessStartInfo startInfo;
        Process process;

        string ret = "";
        try
        {

            startInfo = new ProcessStartInfo(@"c:\python25\python.exe");
            startInfo.WorkingDirectory = workingDirectory;
            if (pyArgs.Length != 0)
                startInfo.Arguments = script + " " + pyArgs;
            else
                startInfo.Arguments = script;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardInput = true;

            process = new Process();
            process.StartInfo = startInfo;


            process.Start();

            // write to standard input
            foreach (string si in standardInput)
            {
                process.StandardInput.WriteLine(si);
            }

            string s;
            while ((s = process.StandardError.ReadLine()) != null)
            {
                ret += s;
                throw new System.Exception(ret);
            }

            while ((s = process.StandardOutput.ReadLine()) != null)
            {
                ret += s;
            }

            return ret;

        }
        catch (System.Exception ex)
        {
            string problem = ex.Message;
            return problem;
        }

    }
like image 101
Justin Avatar answered Oct 12 '22 22:10

Justin


Process.Start should work. if it doesn't, would you post your code and the error you are getting?

like image 40
dance2die Avatar answered Oct 13 '22 00:10

dance2die