C# – First steps with C# and .NET – part 064.
This is a simple example of how to add to the Environment Variable variable Path a simple path read on the admin console. This code first retrieves the current system environment variables using the Environment.GetEnvironmentVariables method. Create a simple project with dotnet tool and add this source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { Console.Write("Enter the path to add: "); string pathToAdd = Console.ReadLine(); Console.WriteLine($"Path to be added: {pathToAdd}"); // Get the current system environment variables var envVariables = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine); // Add the new path to the PATH variable if (envVariables.Contains("Path")) { string currentPath = envVariables["Path"] as string; string newPath = $"{currentPath};{pathToAdd}"; Environment.SetEnvironmentVariable("Path", newPath, EnvironmentVariableTarget.Machine); Console.WriteLine("New path added successfully!"); } else { Console.WriteLine("PATH variable not found!"); } } } |
Depending on the system security level… Read More »