C# 调用命令行执行Cmd命令的操作
更新时间:2021年04月09日 10:51:30 作者:会思考的猴子
这篇文章主要介绍了C# 调用命令行执行Cmd命令的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
1、不知道为啥
process.StartInfo.Arguments = "/c" + "start D:/Tim/Bin/QQScLauncher.exe";
这个执行命令一定要加/c ,/c ,/c,重要的事说3遍 才能正常编译并运行
cmd /c dir
:是执行完dir命令后关闭命令窗口;
cmd /k dir
:是执行完dir命令后不关闭命令窗口。
process.StartInfo.Arguments 我猜测这个调用的是第一张图的窗口,而不是二图的窗口
代码:
static void LaunchCommandLineApp() { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c" + "start D:/Tim/Bin/QQScLauncher.exe"; process.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 process.StartInfo.CreateNoWindow = false; //是否在新窗口中启动该进程的值 (不显示程序窗口) process.Start(); process.WaitForExit(); //等待程序执行完退出进程 process.Close(); }
补充:C# 执行指定命令和执行cmd命令
通常需要在程序执行过程中调用CMD命令并获取信息,
以下方法实现了该功能
/// <summary> /// 执行内部命令(cmd.exe 中的命令) /// </summary> /// <param name="cmdline">命令行</param> /// <returns>执行结果</returns> public static string ExecuteInCmd(string cmdline) { using (var process = new Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine(cmdline + "&exit"); //获取cmd窗口的输出信息 string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); process.Close(); return output; } }
以下方法实现了调用第三方实现的命令
/// <summary> /// 执行外部命令 /// </summary> /// <param name="argument">命令参数</param> /// <param name="application">命令程序路径</param> /// <returns>执行结果</returns> public static string ExecuteOutCmd(string argument, string applocaltion) { using (var process = new Process()) { process.StartInfo.Arguments = argument; process.StartInfo.FileName = applocaltion; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine("exit"); //获取cmd窗口的输出信息 string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); process.Close(); return output; } }
ProcessCore.ExecuteInCmd("ipconfig"); ProcessCore.ExecuteOutCmd("-I http://www.baidu.com", @"C:\curl.exe");
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
相关文章
c# OpenCvSharp实现常见检测(斑点检测,轮廓检测,边缘检测)
这篇文章主要为大家详细介绍了c#如何使用OpenCvSharp实现常见检测(斑点检测,轮廓检测,边缘检测),文中的示例代码讲解详细,需要的小伙伴可以参考下2023-12-12
最新评论