在c#中设置URL协议的路径

时间:2014-09-02 15:36:44

标签: c# path url-protocol

所以我创建了一个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命令)?

1 个答案:

答案 0 :(得分:1)

如果要设置PATH环境变量并在流程中使用它,请将其添加到Environment variables,但在这种情况下您必须将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();
}