Skip to content

Instantly share code, notes, and snippets.

@eebssk1
Created January 17, 2022 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eebssk1/b1fcc21e3457fe85ba284163cedaafa0 to your computer and use it in GitHub Desktop.
Save eebssk1/b1fcc21e3457fe85ba284163cedaafa0 to your computer and use it in GitHub Desktop.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SetMPath
{
internal class Program
{
static int Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(@"No args !");
return -1;
}
if (args[0] != "prepend" && args[0] != "append" && args[0] != "replace")
{
Console.WriteLine(@"Wrong action !");
return -1;
}
string file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
file += @"\reg.txt";
if(!System.IO.File.Exists(file))
{
Console.WriteLine(@"No reg file !");
return -1;
}
string line = System.IO.File.ReadAllLines(file)[0];
if(line == "")
{
Console.WriteLine(@"Reg file empty !");
return -1;
}
string SysKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
string orig = (string)Registry.LocalMachine.CreateSubKey(SysKey).GetValue(@"PATH","",RegistryValueOptions.DoNotExpandEnvironmentNames);
if(orig == "" )
{
Console.WriteLine(@"Cannot get original content !");
return -1;
}
string final;
switch (args[0]){
case "replace":
Registry.LocalMachine.CreateSubKey(SysKey).SetValue(@"PATH", line, RegistryValueKind.ExpandString);
return 0;
case "prepend":
if (!line.EndsWith(@";"))
line += @";";
final = line + orig;
Registry.LocalMachine.CreateSubKey(SysKey).SetValue(@"PATH", final, RegistryValueKind.ExpandString);
return 0;
case "append":
if (line.EndsWith(@";"))
line = line.Remove(line.Length - 1, 1);
if (!orig.EndsWith(@";"))
orig += @";";
final = orig + line;
Registry.LocalMachine.CreateSubKey(SysKey).SetValue(@"PATH", final, RegistryValueKind.ExpandString);
return 0;
}
return -2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment