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

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

一、传递一个参数

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属性中。

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]}");
    }

    // 根据参数进行相应操作...
}

 

 

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangnaisheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值