C# -- 运行Bat文件

运行 .bat 文件

方法1:不关注结果
/**
* 运行bat文件
* 在新窗口调用,忽略返回值
* @param path 绝对路径
*/
public static void runBat(string path)
{
    if (!File.Exists(path))
    {
        //Console.WriteLine("文件不存在!");
        return;
    }

    try
    {
        Process process = new Process();
        FileInfo fileInfo = new FileInfo(path);
        process.StartInfo.WorkingDirectory = fileInfo.Directory.FullName;
        process.StartInfo.FileName = fileInfo.Name;
        process.StartInfo.CreateNoWindow = false;
        process.Start();

        process.WaitForExit();
        process.Close();
    }
    catch (Exception e)
    {
    	Console.WriteLine(e.Message);
    }
}
方法2:
/**
* 运行bat文件
* @param path 绝对路径
* @return 输出内容
*/
public static String runBatBack(string path)
{
    if (!File.Exists(path))
    {
        //Console.WriteLine("文件不存在!");
        return null;
    }
    
	StringBuilder builder = new StringBuilder();
    try
    {
        Process process = new Process();
        FileInfo fileInfo = new FileInfo(path);
        process.StartInfo.WorkingDirectory = fileInfo.Directory.FullName;
        //关闭 shell 文件路径不一样
        process.StartInfo.FileName = path;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true; //重定向输入
        process.StartInfo.RedirectStandardOutput = true; //重定向标准输出 
        process.StartInfo.RedirectStandardError = true; //重定向错误输出
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        //
        StreamReader reader = process.StandardOutput;
        string line = "";//每次读取一行
        while ((line = reader.ReadLine()) != null)
        {
            //Console.WriteLine("message:" + line);
            builder.AppendLine(line);
         }

        process.WaitForExit();
        process.Close();
        reader.Close();
    }
    catch (Exception e)
    {
    	Console.WriteLine(e.Message);
    }

    return builder.ToString();
}

你可能感兴趣的:(C#,-,Winform,c#,开发语言)