You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Win10下两个C#控制台程序交互:输入指令并获取输出方法咨询

在C#控制台程序间实现输入输出交互

步骤1:实现被调用的密码检查程序

这个程序负责读取输入字符串,判断是否匹配预设密码,并输出结果:

using System;

namespace PasswordChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            string correctPassword = "MySecret123"; // 预设密码
            
            Console.WriteLine(input == correctPassword ? "true" : "false");
        }
    }
}

步骤2:实现调用方程序

通过Process类启动密码检查程序,重定向输入输出流来传递数据并获取结果:

using System;
using System.Diagnostics;
using System.Text;

namespace PasswordValidator
{
    class Program
    {
        static void Main(string[] args)
        {
            string testPassword = "MySecret123"; // 要验证的字符串
            string checkerExePath = @"C:\Your\Path\To\PasswordChecker.exe"; // 替换为实际可执行文件路径

            var startInfo = new ProcessStartInfo
            {
                FileName = checkerExePath,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
                StandardOutputEncoding = Encoding.UTF8,
                StandardInputEncoding = Encoding.UTF8
            };

            using (var process = Process.Start(startInfo))
            {
                if (process == null)
                {
                    Console.WriteLine("无法启动密码检查程序");
                    return;
                }

                // 发送要验证的密码
                process.StandardInput.WriteLine(testPassword);
                process.StandardInput.Close(); // 关闭输入流,告知对方输入完成

                // 读取输出结果
                string result = process.StandardOutput.ReadLine()?.Trim() ?? "false";
                process.WaitForExit(); // 等待程序执行完毕

                // 输出验证结果
                Console.WriteLine(result == "true" ? "密码正确" : "密码错误");

                // 读取并输出错误信息(如果有)
                string errorMsg = process.StandardError.ReadToEnd();
                if (!string.IsNullOrWhiteSpace(errorMsg))
                {
                    Console.WriteLine($"错误:{errorMsg}");
                }
            }
        }
    }
}

关键注意事项

  • 重定向配置:必须设置UseShellExecute = false,否则无法启用标准流的重定向。
  • 流的处理:写入输入后关闭StandardInput,确保被调用程序能收到完整输入并结束读取操作。
  • 编码一致性:统一设置输入输出的编码为UTF8,避免跨程序交互时出现乱码。
  • 错误处理:通过StandardError捕获被调用程序的异常或错误输出,便于调试。

内容的提问来源于stack exchange,提问作者Brendan Lynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:07:21