C# 调用控制台程序,并获取输出写入文件

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 using System.Diagnostics;
 7 
 8 namespace CSharpIOTest
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             string file = @"I:\computer_info.cfg";
15             if (File.Exists(file))
16             {
17                 DisplayVersion();
18             
19                 FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
20                 StreamWriter sw = new StreamWriter(fs);
21                 sw.Write(RunCmd("systeminfo"));
22                 sw.Flush();
23                 sw.Close();
24                 System.Console.WriteLine("Write data successfully.\r\n");
25 
26                 FileParse f = new FileParse(file);
27                 System.Console.WriteLine(f.FileContent);
28                 System.Console.WriteLine("read data successfully.\r\n");
29             }            
30         }
31 
32         private static string RunCmd(string cmd)
33         {
34             Process p = new Process();
35             p.StartInfo.FileName = "cmd.exe";
36             p.StartInfo.Arguments = "/c" + cmd;
37             p.StartInfo.UseShellExecute = false;
38             p.StartInfo.RedirectStandardError = true;
39             p.StartInfo.RedirectStandardInput = true;
40             p.StartInfo.RedirectStandardOutput = true;
41             p.StartInfo.CreateNoWindow = true;
42 
43             p.Start();
44             p.StandardInput.WriteLine("exit");
45 
46             return p.StandardOutput.ReadToEnd();
47         }
48 
49         private static void DisplayVersion()
50         {
51             System.Console.ForegroundColor = ConsoleColor.Red;
52             System.Console.WriteLine("Cosmos Copyright 2010 Project");
53             System.Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
54             System.Console.ForegroundColor = ConsoleColor.White;
55             System.Console.Write("test ");
56             System.Console.ForegroundColor = ConsoleColor.Green;
57             System.Console.WriteLine("2013.10.19");
58             System.Console.ForegroundColor = ConsoleColor.White;
59             System.Console.WriteLine();
60         }
61     }
62 }

你可能感兴趣的:(C# 调用控制台程序,并获取输出写入文件)