Reputation: 25
I am currently studying C# from scratch and I stumbled upon a topic that was rather difficult to understand .I want to print out the info about the system in the console. I read about reflections in Troelson and decided to give it a try, so I googled and found a windows form project designed for this problem. I tried to make a similar console application but I sort of get an unhandled exception on the part when I try to print. Any tips on how can I make this work or explanations of what have I done wrong ( and I most certainly have) would be very helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
namespace MachineInfo
{
class Program
{
static void Main(string[] args)
{
Type propertytype = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo[] property = propertytype.GetProperties();
string str;
for(int i=0; i<property.Length; i++ )
{
str = property[i].ToString();
Type prop = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo innerproperty = prop.GetProperty(str);
Console.WriteLine(innerproperty.ToString());
}
}
}
}
Upvotes: 0
Views: 120
Reputation: 101701
You just need:
for(int i=0; i<property.Length; i++ )
{
Console.WriteLine("{0} : {1}",
property[i].Name,
property[i].GetValue(null).ToString());
}
property[i].ToString();
returns the type name which is PropertyInfo
, and you are trying to get a property named PropertyInfo
which is not exists.
Also if you want to get static properties don't forget to specify BindingFlags
var flags = BindingFlags.Public | BindingFlags.Static;
PropertyInfo[] property = propertytype.GetProperties(flags);
Upvotes: 1