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

    // 根据参数进行相应操作...
}
相关推荐
钢铁男儿21 分钟前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群1 小时前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o1 小时前
63、.NET 异常处理
c#·.net·异常处理
SteveDraw4 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
Kookoos4 小时前
性能剖析:在 ABP 框架中集成 MiniProfiler 实现性能可视化诊断
后端·c#·.net·abp vnext·miniprofiler
阿翰6 小时前
自动 GitHub Readme 20 种语言翻译平台 - OpenAiTx 开源免费
c#·.net
枫叶kx10 小时前
1Panel运行的.net程序无法读取系统字体(因为使用了docker)
c#
军训猫猫头15 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
不爱写代码的玉子17 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
开开心心就好20 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法