我如何在C#中执行一个shell脚本?

6

我有一个包含Unix shell脚本的文件。现在我想在.NET中运行相同的脚本,但是我无法执行它。

我的问题是,是否可能在.NET中运行Unix程序?是否有类似于Objective-C中NSTask的API来运行Unix shell脚本,那么.NET中是否有类似的API呢?


1
我假设 .net 程序在 Linux 上以 Mono 运行。对吗? - Corey Ogburn
@corey,op想要在.net中执行Unix shell脚本的任何API吗? - Hussain Shabbir
2个回答

8

这个问题之前已经有人回答过了,你可以查看这里

另外,你可以使用以下方法:

Process proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

然后启动该进程并从中读取:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    // Do something with line
}

这对于Windows文件很好用。这对于Linux文件也适用吗? - gunr2171
实际上我没有在Linux上测试过这个...但在Windows上它运行良好。 - Pouya Samie

0
        ProcessStartInfo frCreationInf = new ProcessStartInfo();
        frCreationInf.FileName = @"C:\Program Files\Git\git-bash.exe";
        frCreationInf.Arguments = "Test.sh";
        frCreationInf.UseShellExecute = false;
        var process = new Process(); 
        process.StartInfo = frCreationInf;
        process.Start();
        process.WaitForExit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接