雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

C#调用执行命令行窗口 (CMD)

2024-07-23 49

在C#中,有时需要执行命令行指令来完成特定的任务。这可能包括运行脚本、管理服务、获取系统信息等。C# 提供了 System.Diagnostics 命名空间中的 Process 类来启动和管理系统进程,包括命令行窗口(cmd.exe)。

C# 调用命令行应用场景

自动化构建和部署:使用命令行工具如 MSBuild 或者 PowerShell 脚本来编译和部署应用程序。

系统管理:执行系统管理任务,如启动或停止服务,管理文件和目录等。

网络操作:运行网络诊断工具如 ping、ipconfig 或自定义网络操作脚本。

数据库操作:执行数据库备份、还原或运行 SQL 脚本。

第三方工具集成:调用 Git、Docker 或其他命令行工具进行自动化操作。

示例 1: C#执行简单命令

public class CmdExample
{
    public static void ExecuteCommand(string command)
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", $"/c {command}")
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (Process process = Process.Start(processStartInfo))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
            }
        }
    }
}

使用此方法可以执行任何简单的命令行指令。例如,获取当前目录下的文件列表:

static void Main()
{
    CmdExample.ExecuteCommand("dir");
}

示例 2: 运行批处理脚本

public class BatchScriptRunner
{
    public static void RunBatchScript(string scriptPath)
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo(scriptPath)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (Process process = Process.Start(processStartInfo))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
            }
        }
    }
}

调用批处理脚本 a.bat:

static void Main()
{
    BatchScriptRunner.RunBatchScript(@"d:\a.bat");
}

示例 3: 执行具有复杂输出的命令

public class ComplexCommandExecutor
{
    public static void ExecuteComplexCommand(string command)
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", $"/c {command}")
        {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        StringBuilder output = new StringBuilder();
        StringBuilder error = new StringBuilder();

        using (Process process = new Process())
        {
            process.StartInfo = processStartInfo;
            process.OutputDataReceived += (sender, args) => output.AppendLine(args.Data);
            process.ErrorDataReceived += (sender, args) => error.AppendLine(args.Data);

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();

            Console.WriteLine("Output:");
            Console.WriteLine(output.ToString());
            Console.WriteLine("Error:");
            Console.WriteLine(error.ToString());
        }
    }
}
static void Main()
{
    ComplexCommandExecutor.ExecuteComplexCommand("ipconfig /all");
}

在C#中调用执行命令行窗口可以非常灵活和强大,但也需要注意安全性和错误处理。始终验证外部输入,避免注入攻击,并确保处理任何可能的异常和错误输出。正确使用时,它可以是自动化和系统集成的强大工具。

更新于:1个月前
赞一波!

文章评论

全部评论