C# 调用命令行执行Cmd命令的操作

Yolanda ·
更新时间:2024-09-21
· 26 次阅读

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");

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。如有错误或未考虑完全的地方,望不吝赐教。



调用 cmd命令 命令行 C#

需要 登录 后方可回复, 如果你还没有账号请 注册新账号