程序调用CMD&输出重定向到指定文件
来源:互联网 发布:linux 卸载svn1.7 编辑:程序博客网 时间:2024/04/28 23:39
题记:在自己的程序中调用CMD执行某个命令,将结果输出到某文件保存,以供使用
两种方法:
1、调用CMD后逐行读取写入文件
2、使用CMD的重定向输出命令
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(); } } } }}
- 程序调用CMD&输出重定向到指定文件
- 关于将程序输出重定向到文件的实现
- VBS读取cmd命令的输出,VBS执行程序后重定向到VBS
- 将windows命令行的结果保存到文件 (cmd命令的重定向输出)
- 将windows命令行的结果保存到文件 (cmd命令的重定向输出)
- cmd chcp命令切换字符格式 cmd重定向输出到文件出现中文乱码的处理方法
- linux 实现输出重定向(printf 打印,输出到指定文件(不输出到终端))
- cmd命令重定向输出
- printf重定向输出到文件
- vc6 printf重定向输出到文件
- 重定向输出以追加到文件
- 将make 输出重定向到文件
- 重定向子进程输出到文件
- (41)重定向到文件输出
- eclipse控制台输出重定向到文件
- Drozer输出重定向到文件
- 重定向 NSLog 输出到文件
- C++重定向到输出文件
- thinkphp总结 -- 不断更新中..
- sakai修改sakai.properties的字段为中文运行后出现乱码的问题分析与解决方案!
- C语言删除一个字符串中的多余空格字符
- i2c实例讲解
- SQL SERVER复习笔记02
- 程序调用CMD&输出重定向到指定文件
- 字符,字节和编码
- s3c2410_gpio_cfgpin等内核导出函数
- 山区行
- ANSI字符,UNICODE,宽字符,窄字符,多字节字符集
- android应用 总结
- linux bash shell之变量替换::=句法、=句法、:-句法、-句法、=?句法、?句法、:+句法、+句法
- 模仿360android手机卫士 仿w8界面,右边滑出按钮条
- 字典树 C++