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

    // 根据参数进行相应操作...
}
相关推荐
枯萎穿心攻击5 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
小码编匠5 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果5 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
阿蒙Amon13 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust16 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back17 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon18 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员19 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
开开心心_Every19 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony