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

    // 根据参数进行相应操作...
}
相关推荐
未来之窗软件服务17 小时前
操作系统应用(三十七)C#华旭金卡身份证SDK-HX-FDX3S—东方仙盟筑基期
开发语言·c#·身份证阅读器·酒店管理系统·仙盟创梦ide
切糕师学AI17 小时前
C# 如何回收整个 EF(DbContext)对象及其相关实体的内存?
c#·gc·垃圾回收·ef
momo小菜pa18 小时前
C#--BindingList
开发语言·c#
我是唐青枫18 小时前
C# 列表模式(List Patterns)深度解析:模式匹配再进化!
c#·.net
云草桑18 小时前
Net 模拟退火,遗传算法,禁忌搜索,神经网络 ,并将 APS 排程算法集成到 ABP vNext 中
c#·.net·制造
范小多18 小时前
mysql实战 C# 访问mysql(连载三)
数据库·mysql·oracle·c#
我是唐青枫21 小时前
C# 泛型数学:解锁真正的类型安全数值运算
c#·.net
故事不长丨1 天前
C#定时器与延时操作的使用
开发语言·c#·.net·线程·定时器·winform
阿桂有点桂1 天前
C#使用VS软件打包msi安装包
windows·vscode·c#
c#上位机1 天前
halcon图像增强之分段灰度拉伸2
c#·上位机·halcon·机器视觉