c#利用脚本,本地执行linux命令

如题,需要注意脚本的编码应该是ascii(阿里的centos8上是这样)。代码:using System;using System.Diagnostics;using System.IO;using System.Text;namespace mylinux{class Program{static void Main(string...

如题,需要注意脚本的编码应该是ascii(阿里的centos8上是这样)。

代码:

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace mylinux
{
    class Program
    {
        static void Main(string[] args)
        {
            setCommand();
            doSh();

        }
        static void setCommand()
        {
            StreamWriter sw = new StreamWriter("test.sh", false, Encoding.ASCII);
            string t = "";
            sw.WriteLine("#!/bin/bash");
            Console.WriteLine("请输入Linux脚本命令(exit退出):");
            t = Console.ReadLine();
            while(t.ToLower()!="exit")
            {
                sw.WriteLine(t);
                Console.WriteLine("请输入Linux脚本命令(exit退出):");
                t = Console.ReadLine();
            }
            sw.Close();
        }
        static void doSh()
        {
            Process process = new Process();
            process.StartInfo.FileName = "sh";
            process.StartInfo.Arguments = "test.sh";
            process.Start();
            process.WaitForExit();
            process.Close();
        }
    }
}

运行结果:

 

本文标题为:c#利用脚本,本地执行linux命令

基础教程推荐