『C#基础』调用CMD的一个小工具

本文介绍了一款使用 C# 开发的实用工具,该工具能够调用 CMD.exe 执行命令并获取结果,例如查看 IP 和 Ping 网址等。通过 WPF 界面,用户可以轻松地输入命令并查看执行结果。

由于经常要使用CMD的一些命令,比如查看IP,Ping一个网址之类的。于是就写了一个调用CMD.exe的小工具。

主要就是实现这样一个事情:调用CMD.exe然后传给它我想要执行的命令,最后获取结果。

界面:

image

image

代码:

主要执行代码using System.Diagnostics;
using System.IO;

namespace Client
{
    class ExcuteCMD
    {
        static Process p = new Process();
        public static string Excute(string cmd)
        {
            //创建Process对象
            p.StartInfo.FileName = "cmd.exe";          //要调用的程序 
            p.StartInfo.UseShellExecute = false;       //关闭Shell的使用 
            p.StartInfo.RedirectStandardInput = true;  //重定向标准输入 
            p.StartInfo.RedirectStandardOutput = true; //重定向标准输出 
            p.StartInfo.RedirectStandardError = true;  //重定向错误输出 
            p.StartInfo.CreateNoWindow = true;         //设置不显示窗口 

            p.Start();  //启动进程 
            p.StandardInput.WriteLine(cmd); //要执行的命令 
            p.StandardInput.WriteLine("exit");
            #region 吸收版权信息
            p.StandardOutput.ReadLine();
            p.StandardOutput.ReadLine();
            p.StandardOutput.ReadLine();
            p.StandardOutput.ReadLine();
            p.StandardOutput.ReadLine();
            #endregion
            string strRst = p.StandardOutput.ReadToEnd();  //从输出流获取命令执行结果 
             // logOut(strRst,cmd); // 记录执行到日志文件

            return strRst;
        }
        public static void closeCMD()
        {
            p.Close();
        }
        private static void logOut(string log,string cmd)
        {
            FileStream fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);

            sw.Flush();

            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(cmd + log);
            sw.WriteLine();

            sw.Flush();
            sw.Close();
            fs.Close(); 
        }
    }
}

WPF界面代码using System.Windows;
using System.Windows.Input;

namespace Client
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            tbCmd.Focus();
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = ExcuteCMD.Excute(tbCmd.Text);            
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            ExcuteCMD.closeCMD();
            this.Close();
        }

        private void btnPingQQ_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = ExcuteCMD.Excute("Ping www.qq.com");
        }

        private void btnIPConfig_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = ExcuteCMD.Excute("ipconfig");
        }

        private void tbCmd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSubmit_Click(sender, e);
            }
        }
    }
}


WPF界面代码<Window x:Class="Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CMD命令执行工具" Height="300" Width="478" MinWidth="400" MinHeight="300" Icon="/Client;component/Images/21.ico">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="210*" />
            <RowDefinition Height="28*" />
            <RowDefinition Height="23*" />
        </Grid.RowDefinitions>
        <Button Content="执行" Height="23" Margin="0,0,66,5" Name="btnSubmit" VerticalAlignment="Bottom" TabIndex="2" Click="btnSubmit_Click" HorizontalAlignment="Right" Width="60" Grid.Row="1" />
        <TextBox Height="23" Name="tbCmd" VerticalAlignment="Bottom" Margin="0,0,132,5" TabIndex="1" Grid.Row="1" KeyDown="tbCmd_KeyDown" />
        <Button Content="结束" Height="23" HorizontalAlignment="Right" Margin="0,0,0,5" Name="btnClose" VerticalAlignment="Bottom" Width="60" Click="btnClose_Click" Grid.Row="1" />
        <ScrollViewer HorizontalAlignment="Stretch" Name="scrollViewer1" VerticalAlignment="Stretch">
            <Label Height="Auto" Name="lblResult" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </ScrollViewer>
        <Button Content="PingQQ" Height="23" HorizontalAlignment="Left" Name="btnPingQQ" VerticalAlignment="Top" Width="56" Click="btnPingQQ_Click" Grid.Row="2" />
        <Button Content="IPConfig" Height="23" HorizontalAlignment="Left" Margin="62,0,0,0" Name="btnIPConfig" VerticalAlignment="Top" Width="56" Click="btnIPConfig_Click" Grid.Row="2" />
    </Grid>
</Window>


转载于:https://my.oschina.net/skyler/blog/706086

### 在 C#调用 CMD 命令的完整示例 在 C# 程序中调用 CMD 命令可以通过 `System.Diagnostics.Process` 类实现,该类提供了创建和管理本地或远程进程的功能。以下是一个完整的代码示例,展示了如何通过 C# 调用 CMD 并执行命令[^1]。 ```csharp using System; using System.Diagnostics; class Program { static void Main() { // 创建 ProcessStartInfo 对象以配置 CMD 进程 ProcessStartInfo startInfo = new ProcessStartInfo { FileName = "cmd.exe", // 指定启动的程序为 CMD RedirectStandardInput = true, // 重定向标准输入以便发送命令 RedirectStandardOutput = true, // 重定向标准输出以便读取结果 RedirectStandardError = true, // 重定向错误输出以便捕获错误信息 UseShellExecute = false, // 必须设置为 false 才能启用重定向 CreateNoWindow = true // 不显示 CMD 窗口 }; try { using (Process process = new Process()) // 创建 Process 实例 { process.StartInfo = startInfo; // 设置启动信息 process.Start(); // 启动 CMD 进程 // 向 CMD 发送命令 process.StandardInput.WriteLine("dir"); // 示例命令:列出当前目录内容 process.StandardInput.WriteLine("exit"); // 发送退出命令以结束 CMD 进程 // 读取命令的输出结果 string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); // 等待进程退出 process.WaitForExit(); // 输出结果 Console.WriteLine("CMD Output:"); Console.WriteLine(output); if (!string.IsNullOrEmpty(error)) { Console.WriteLine("CMD Error:"); Console.WriteLine(error); } } } catch (Exception ex) { Console.WriteLine($"发生异常: {ex.Message}"); } } } ``` #### 代码解析 - 使用 `ProcessStartInfo` 配置 CMD 进程的启动参数,包括重定向标准输入、输出和错误流[^4]。 - 设置 `UseShellExecute` 为 `false` 是为了启用标准流的重定向功能[^4]。 - 通过 `process.StandardInput.WriteLine` 方法向 CMD 发送命令,并使用 `process.StandardOutput.ReadToEnd` 和 `process.StandardError.ReadToEnd` 方法捕获命令的输出和错误信息[^4]。 - 最后,调用 `process.WaitForExit()` 确保等待 CMD 进程完成后再继续执行后续代码。 #### 注意事项 - 如果需要执行多个命令,可以在每条命令之间用 `&` 或 `&&` 连接,或者依次通过 `StandardInput.WriteLine` 发送命令[^3]。 - 当执行涉及文件路径的命令时,确保路径中的空格被正确处理,例如使用引号包裹路径。 - 对于长时间运行的命令,建议设置超时机制以避免程序卡死[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值