-1

所以我创建了一个 URL 协议来运行带有命令参数的应用程序。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;

namespace iw4Protocol
{
    class Program
    {
        static void Main(string[] args)
        {
            RegistryKey key = Registry.ClassesRoot.OpenSubKey("gameProtocol");

            if (key == null)
            {
                string iw4FullPath = Directory.GetCurrentDirectory();

                gameProtocol protocol = new gameProtocol();
                protocol.RegisterProtocol(gameFullPath);
            }
            else
            {
                RegistryKey gamepathkey = Registry.ClassesRoot.OpenSubKey("gameProtocol");
                string gamepath = gamepathkey.GetValue("gamepath").ToString();

                Environment.SetEnvironmentVariable("path",gamepath);



                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = @"test.exe";
                startInfo.Arguments = Environment.CommandLine;
                Process.Start(startInfo);
            }
        }
    }
}

问题是程序需要一些文件才能启动,但由于路径未“设置”而无法加载它们。

我如何设置这个路径来启动所有这些需要的文件(比如/cd命令)?

4

1 回答 1

1

如果要设置 PATH 环境变量并在进程中使用它,请将其添加到环境变量中,但在这种情况下您必须设置UseShellExecute为 false:

ProcessStartInfo startInfo = new ProcessStartInfo();
// set environment
startInfo.UseShellExecute = false;
startInfo.EnvironmentVariables["PATH"] += ";" + gamepath;
// you might need more Environment vars, you're on your own here...
// start the exe
startInfo.FileName = @"test.exe";
startInfo.Arguments = Environment.CommandLine;

// added for debugging

startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;


var p = new Process();
p.StartInfo = startInfo;

using(var sw = new StreamWriter(File.Create("c:\\temp\\debug.txt"))) // make sure C:\temp exist
{
    p.OutputDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);
    p.ErrorDataReceived += (sender, pargs) => sw.WriteLine(pargs.Data);

    p.Start();
    p.BeginOutputReadLine();
    p.BeginErrorReadLine();

    p.WaitForExit();
}
于 2014-09-02T16:28:03.720 回答