C# 程序启动另外一个exe的时候传参数

C# 程序启动另外一个exe的时候传参数

一、传递一个参数

cs 复制代码
using System.Diagnostics;

public void StartAnotherProcessWithArguments()
{
    // 创建ProcessStartInfo实例
    ProcessStartInfo startInfo = new ProcessStartInfo();

    // 设置要执行的程序路径
    startInfo.FileName = @"C:\Path\To\Your\Executable.exe";

    // 设置传递给程序的参数
    startInfo.Arguments = @"C:\Some\Other\Path"; // 这里填入作为参数传递的路径

    // 设置其他选项,如是否使用Shell执行(这里假设不需要)
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true; // 如果不需要显示窗口

    // 创建并启动进程
    using (Process process = new Process())
    {
        process.StartInfo = startInfo;
        process.Start();
    }
}

// 接收参数的被启动程序的Main方法示例:
using System;

class YourProgram
{
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            string receivedPath = args[0]; // 获取第一个参数,假设这就是我们传递的路径

            Console.WriteLine($"Received path: {receivedPath}");

            // 在这里处理接收到的路径
            // ...
        }
        else
        {
            Console.WriteLine("No argument was passed.");
        }
    }
}

二、传递多个参数

启动另一个exe并需要传递多个参数时,可以将所有参数作为单个字符串,在参数之间用空格分隔,然后设置到ProcessStartInfo.Arguments属性中。

cs 复制代码
using System.Diagnostics;

public void StartAnotherProcessWithArguments()
{
    // 创建ProcessStartInfo实例
    ProcessStartInfo startInfo = new ProcessStartInfo();

    // 设置要执行的程序路径
    startInfo.FileName = @"C:\Path\To\Your\Executable.exe";

    // 设置传递给程序的参数
    // 假设我们有两个参数,一个是路径,另一个是选项
    string arg1 = @"C:\Some\Path";
    string arg2 = "OptionValue";
    startInfo.Arguments = $"{arg1} {arg2}";

    // 设置其他选项,如是否使用Shell执行(这里假设不需要)
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true; // 如果不需要显示窗口

    // 创建并启动进程
    using (Process process = new Process())
    {
        process.StartInfo = startInfo;
        process.Start();
    }
}

// 接收参数的被启动程序的Main方法示例:
static void Main(string[] args)
{
    // 参数会被解析为字符串数组
    // args[0] 应该是 "C:\Some\Path"
    // args[1] 应该是 "OptionValue"

    Console.WriteLine($"参数数量: {args.Length}");
    for (int i = 0; i < args.Length; i++)
    {
        Console.WriteLine($"参数{i}: {args[i]}");
    }

    // 根据参数进行相应操作...
}
相关推荐
清风与日月6 分钟前
c# 上位机作为控制端与下位机通信方式
单片机·嵌入式硬件·c#
烛阴2 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#
yue0083 小时前
C# 生成指定位数的编号
开发语言·c#
红黑色的圣西罗3 小时前
C# List.Sort方法总结
开发语言·c#
夏霞6 小时前
c# ASP.NET Core SignalR 客户端配置自动重连次数
c#·.netcore
2501_930707787 小时前
使用C#代码在 Word 文档中查找并替换文本
开发语言·c#·word
一个帅气昵称啊9 小时前
在.NET中使用RAG检索增强AI基于Qdrant的矢量化数据库
ai·性能优化·c#·.net·rag·qdrant
还是大剑师兰特11 小时前
C#面试题及详细答案120道(86-95)-- 进阶特性
c#·大剑师
我是唐青枫13 小时前
C#.NET ControllerBase 深入解析:Web API 控制器的核心基石
c#·.net