c# winform调用cmd命令+写bat脚本并执行

您所在的位置:网站首页 bat文件编写自动运行cmd命令 c# winform调用cmd命令+写bat脚本并执行

c# winform调用cmd命令+写bat脚本并执行

2024-06-02 05:42| 来源: 网络整理| 查看: 265

0

  调用 cmd(Command Prompt)是一种常见的操作系统间的交互方式。在 C# 中调用 cmd 可以实现一些系统级的操作,比如执行命令行工具,管理系统资源等。它的优势和缺点如下:

优势:

强大的系统级操作:通过调用 cmd,可以执行各种系统命令,如创建、删除、复制、移动文件和文件夹等。这使得编程人员可以更方便地进行系统级的操作,而不需要自己编写复杂的代码。

调用外部工具:有些功能无法用 C# 直接实现,但可以通过调用 cmd 执行相应的命令行工具来实现。这样可以充分利用现有的工具和资源,提高开发效率。

灵活性和可扩展性:cmd 提供了丰富的命令和选项,可以满足各种操作需求。而且可以通过批处理脚本编写复杂的操作流程,提高代码的可读性和可维护性。

缺点:

系统依赖性:调用 cmd 是依赖于操作系统的,不同的操作系统可能有不同的 cmd 命令和选项。因此,需要编写不同的代码来适配不同的操作系统,增加了开发的复杂性。

安全性和稳定性:调用 cmd 可能涉及到系统敏感的操作,如创建、删除文件等,如果权限不当或者错误操作可能导致系统崩溃或者数据丢失。对于一些关键操作,需要特别小心和谨慎处理,以保证系统的安全和稳定。

可移植性:调用 cmd 会使代码与操作系统紧密耦合,降低了代码的可移植性。如果需要在多个操作系统上运行,需要对代码进行适配和修改,增加了开发和维护的成本。

1 执行cmd命令+bat脚本创建和执行 创建winform应用程序,加载两个buttom、一个panel容器和一个pictureBox控件,用于触发cmd命令的执行和结果的显示。 在这里插入图片描述第一个button1点击事件下写执行cmd命令的功能,执行了一句创建文件夹的命令,执行之后会在D盘创建一个临时文件夹,如果文件夹已存在会先删除再创建; private void button1_Click_1(object sender, EventArgs e) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe "; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 p.Start(); //执行的命令,在D盘创建一个文件夹 p.StandardInput.WriteLine(@"rd /s /q D:\testCMD"); p.StandardInput.WriteLine(@"md D:\testCMD"); p.StandardInput.AutoFlush = true; p.StandardInput.WriteLine("exit"); p.Close(); } 第二个button2点击事件下是创建*.bat脚本文件和执行.bat脚本的方法,该脚本执行一段GMT程序返回一地学图件,GMT就属于一外部工具,暂时不知道怎么通过c#直接调用,只能用脚本的方式控制执行; private void button2_Click(object sender, EventArgs e) { string batfile; writeBat(out batfile); // 写bat脚本 cal_bat(batfile); // 执行bat脚本 if (File.Exists(@"D:\\testCMD\\01.jpg")) { pictureBox1.Image = Image.FromFile(@"D:\\testCMD\\01.jpg"); //加载bat执行后结果 } }

执行结果如下 在这里插入图片描述

2 完整代码

注:程序要顺利执行要安装GMT工具,此代码仅做示例

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CarryCmd { public partial class Form1 : Form { [DllImport("User32.dll ", EntryPoint = "SetParent")] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [DllImport("user32.dll ", EntryPoint = "ShowWindow")] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click_1(object sender, EventArgs e) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe "; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 p.Start(); //执行的命令,在D盘创建一个文件夹 p.StandardInput.WriteLine(@"rd /s /q D:\testCMD"); p.StandardInput.WriteLine(@"md D:\testCMD"); p.StandardInput.AutoFlush = true; p.StandardInput.WriteLine("exit"); p.Close(); } /// /// 写bat文件 /// /// public static void writeBat(out string batfile) { string pathRoot = @"D:\testCMD"; // button1调用cmd创建的路径; if (!Directory.Exists(pathRoot)) // 判断路径是否存在 { MessageBox.Show("先执行button1,建立根目录!"); batfile = ""; return; } batfile = pathRoot + @"\testBat.bat"; if (File.Exists(batfile)) { File.Delete(batfile); } FileStream fs1 = new FileStream(batfile, FileMode.Create, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fs1); sw.WriteLine(@"set ps=01.ps"); sw.WriteLine(@"gmt gmtset MAP_GRID_CROSS_SIZE_PRIMARY 0 FONT_ANNOT_PRIMARY 10p"); sw.WriteLine(@"gmt psbasemap -R0/6.5/0/3.5 -Jx1i -B0 -P -K > %ps%"); sw.WriteLine(@"gmt pscoast -Rg -JH0/6i -X0.25i -Y0.2i -O -Bg30 -Dc -Glightbrown -Slightblue >> %ps%"); sw.WriteLine(@"gmt psconvert -A0.2c -E500 %ps%"); // 11 删除没用的东西 sw.WriteLine("del .gmt*"); sw.WriteLine("del ?.cpt"); sw.WriteLine("del tmp"); sw.WriteLine("del gmt.conf"); sw.Close(); fs1.Close(); } //执行bat脚本文件 // batfile输入bat文件路径 public void cal_bat(string batfile) { Process proc = null; try { proc = new Process(); proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batfile); proc.StartInfo.FileName = Path.GetFileName(batfile); proc.StartInfo.Arguments = string.Format("10");//this is argument proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; proc.Start(); System.Threading.Thread.Sleep(100);//加上,100如果效果没有就继续加大 SetParent(proc.MainWindowHandle, panel2.Handle); // 要显示外部程序的容器 ShowWindow(proc.MainWindowHandle, 3); proc.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); } } private void button2_Click(object sender, EventArgs e) { string batfile; writeBat(out batfile); cal_bat(batfile); if (File.Exists(@"D:\\testCMD\\01.jpg")) { pictureBox1.Image = Image.FromFile(@"D:\\testCMD\\01.jpg"); } } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3