c#执行外部命令示例分享
string command = @"python test.py";
string output = execute.run(command);
console.writeline(output);
using system;
using system.collections.generic;
using system.diagnostics;
using system.linq;
using system.text;
using system.text.regularexpressions;
//using before change the namespace
namespace test.utility
{
class execute
{
public static string run(string command)
{
string output = null;
if (command != null && !command.equals(""))
{
process process = new process();
processstartinfo processstartinfo = new processstartinfo();
processstartinfo.filename = "cmd.exe";
//no create the cmd windows
processstartinfo.createnowindow = true;
processstartinfo.redirectstandardinput = true;
processstartinfo.redirectstandardoutput = true;
processstartinfo.redirectstandarderror = true;
processstartinfo.useshellexecute = false;
process.startinfo = processstartinfo;
try
{
process.start();
process.standardinput.writeline(command);
process.standardinput.writeline("exit");
process.waitforexit(30 * 1000);
output = process.standardoutput.readtoend();
}
catch (exception e)
{
process.close();
return e.tostring();
}
finally
{
process.close();
}
}
return contextfilter(output);
}
public static string contextfilter(string output)
{
regex regex_end = new regex("^[^^]*#end");
match match = regex_end.match(output);
regex regex_begin = new regex("^[^^]*?#begin\r\n");
string result = regex_begin.replace(match.value, "");
regex regex_tar = new regex("\r\n#end$");
result = regex_tar.replace(result,"");
return result;
}
}
}
上一篇: Asp.Net中索引器的用法分析