You don't need reflection here
foreach(DictionaryEntry e in System.Environment.GetEnvironmentVariables())
{
Console.WriteLine(e.Key + ":" + e.Value);
}
var compName = System.Environment.GetEnvironmentVariables()["COMPUTERNAME"];
Question
We have a little task to print in a console window all the variables of the Environment
class using reflection
, but how to do so I don't even have a clue. I am sorry if I've written anything wrong here, I'm new to C#
.
Of course I could use this kind of code, but that is not what is required from me.
string machineName = System.Environment.MachineName;
Console.WriteLine(machineName);
I searched Google so much and this is what I found, but I don't think this is what I need. I don't even know what I need.
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);
Any suggestions, clues?
Solution
You don't need reflection here
foreach(DictionaryEntry e in System.Environment.GetEnvironmentVariables())
{
Console.WriteLine(e.Key + ":" + e.Value);
}
var compName = System.Environment.GetEnvironmentVariables()["COMPUTERNAME"];
OTHER TIPS
Get the all public and static properties of Environment
using GetProperties
method, then display the name and the value of each property:
var properties = typeof(Environment)
.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach(var prop in properties)
Console.WriteLine("{0} : {1}", prop.Name, prop.GetValue(null));
Although it's an old question, there is a neater possible answer based on the accepted answer, using Linq:
IEnumerable<string> environmentVariables = Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Select(de => $"{de.Key}={de.Value}");
Console.WriteLine("Environment Variables: " + string.Join(Environment.NewLine, environmentVariables));
Or, a shorter version of the same code:
Console.WriteLine("Environment Variables: " + string.Join(Environment.NewLine,
Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Select(de => $"{de.Key}={de.Value}")));