Set Path for URL Protocol in c#

626 views Asked by At

So I created an URL protocol to run an application with the command arguments.

Here is my code:

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

The problem is that the program need some files to get launched but it can't load them because the path isn't 'set'.

How I can set this path to launch all these needed files (like /cd command)?

1

There are 1 answers

5
rene On

If you want to set the PATH environment variable and use it in your process, add it to the Environment variables but you have to set UseShellExecute to false in that case:

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();
}