您的位置:首页 > 其它

程序调用CMD&输出重定向到指定文件

2012-09-22 15:58 393 查看
题记:在自己的程序中调用CMD执行某个命令,将结果输出到某文件保存,以供使用

两种方法:

1、调用CMD后逐行读取写入文件

2、使用CMD的重定向输出命令

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace aboutls
{
internal class DosCommandDo
{
public static void Execute(string dosCommand, string fileName, int milliseconds)
{
if (dosCommand != null && dosCommand != "")
{
//TODO judgement the fileName
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c " + dosCommand;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;

try
{
if (process.Start())
{
if (milliseconds == 0)
process.WaitForExit();
else
process.WaitForExit(milliseconds);

System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName,
false, System.Text.Encoding.GetEncoding("gb2312"));
System.IO.StreamReader reader = process.StandardOutput;//截取输出流
string line = reader.ReadLine();//每次读取一行
sw.WriteLine(line);
sw.Flush();

while (!reader.EndOfStream)
{
line = reader.ReadLine();
sw.WriteLine(line);
sw.Flush();
}

if (reader != null)
reader.Close();
if (sw != null)
sw.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (process != null)
process.Close();
}
}
}

public static void ExecuteOut(string dosCommand, string fileName, int milliseconds)
{
if (dosCommand != null && dosCommand != "")
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c " + dosCommand + " > "+fileName;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;

try
{
if (process.Start())
{
if (milliseconds == 0)
process.WaitForExit();
else
process.WaitForExit(milliseconds);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (process != null)

process.Close();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐