Skip to content

Instantly share code, notes, and snippets.

@czyt
Created July 19, 2023 13:45
Show Gist options
  • Save czyt/bbaadb9a751da809a725c347464ae22a to your computer and use it in GitHub Desktop.
Save czyt/bbaadb9a751da809a725c347464ae22a to your computer and use it in GitHub Desktop.
write app current working dir to windows system Path
using System;
using System.Security.Principal;
namespace AddCurrentDirToPath
{
internal class Program
{
const string envPathKey = "Path";
public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static void Main(string[] args)
{
if (!IsAdministrator())
{
Console.WriteLine("请以管理员身份运行本程序!!🤭");
Console.ReadKey();
return;
}
var currentDir = Environment.CurrentDirectory;
var currentPathEnv = Environment.GetEnvironmentVariable(envPathKey, EnvironmentVariableTarget.Machine);
if (currentPathEnv.Contains(currentDir))
{
Console.WriteLine($"当前路径:{currentDir}已经包含在Path环境变量中!!😟");
Console.ReadKey();
return;
}
var newPathEnv = $"{currentPathEnv};{currentDir}";
Environment.SetEnvironmentVariable(envPathKey, newPathEnv, EnvironmentVariableTarget.Machine);
Console.WriteLine("写入环境变量操作完成!🎉");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment