在c#中设置URL协议的路径
本文关键字:协议 路径 URL 设置 | 更新日期: 2023-09-27 18:20:18
所以我创建了一个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
命令)?
如果您想设置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();
}