Skip to content

Instantly share code, notes, and snippets.

@czyt
Created July 19, 2023 13:45
Show Gist options
  • Select an option

  • Save czyt/bbaadb9a751da809a725c347464ae22a to your computer and use it in GitHub Desktop.

Select an option

Save czyt/bbaadb9a751da809a725c347464ae22a to your computer and use it in GitHub Desktop.

Revisions

  1. czyt created this gist Jul 19, 2023.
    42 changes: 42 additions & 0 deletions systemenv.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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();
    }
    }
    }