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

时间:2023-03-10 04:16:39
C# 调用控制台程序,并获取输出写入文件
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics; namespace CSharpIOTest
{
class Program
{
static void Main(string[] args)
{
string file = @"I:\computer_info.cfg";
if (File.Exists(file))
{
DisplayVersion(); FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(RunCmd("systeminfo"));
sw.Flush();
sw.Close();
System.Console.WriteLine("Write data successfully.\r\n"); FileParse f = new FileParse(file);
System.Console.WriteLine(f.FileContent);
System.Console.WriteLine("read data successfully.\r\n");
}
} private static string RunCmd(string cmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c" + cmd;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true; p.Start();
p.StandardInput.WriteLine("exit"); return p.StandardOutput.ReadToEnd();
} private static void DisplayVersion()
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Cosmos Copyright 2010 Project");
System.Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.Console.ForegroundColor = ConsoleColor.White;
System.Console.Write("test ");
System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine("2013.10.19");
System.Console.ForegroundColor = ConsoleColor.White;
System.Console.WriteLine();
}
}
}

FileParse.cs:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace CSharpIOTest
{
class FileParse
{
private string filePath;//文件路径
private string fileName;//文件名
private string fileContent;//文件内容 public FileParse()
{
filePath = string.Empty;
fileName = string.Empty;
fileContent = string.Empty;
} public FileParse(string file)
{
filePath = file;
} public string FilePath
{
set { filePath = value; }
get { return filePath; }
} public string FileName
{
set { fileName = value; }
get { return fileName; }
} public string FileContent
{
set { fileContent = value; }
get
{
if (File.Exists(filePath))
{
FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
return sr.ReadToEnd();
}
else
{
System.Console.WriteLine("file is empty.\r\n");
return string.Empty;
}
}
}
}
}