I have to read, in C#, a file .ini, where each section correspond to a static Class and the values in each section correspond to a property of the class. I do an example:
[Database]
path='test.db'
userid='root'
password=123123
I have created a class Database in this way
public static class DataBase
{
public static string userId;
public static string psw;
public static string path;
}
So when I read [Database] i have to read all the parameters and if the name of this one is present in the Database class i have to set his value.
How I can do that? I think I must use Reflection but I can't use it.
I post the code that I've written but when reach this row, elencoProprietà is null.
var elencoProprietà = tipo.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Program t = new Program();
//t.Run();
var testo = @"[Database]
path='test.db'
userid=12
password=black";
//Ini parser
var parser = new IniParser.Parser.IniDataParser();
var dati = parser.Parse(testo);
string assemblyName = "ConsoleApplication1";
string namespaceName = "ConsoleApplication1";
//Print section count
Console.WriteLine("Section number: " + dati.Sections.Count);
foreach (var sezione in dati.Sections)
{
string fullName = string.Format("{0}.{1}, {2}", namespaceName, sezione.SectionName, assemblyName);
Type tipo = Type.GetType(fullName, throwOnError: false, ignoreCase: true);
Console.WriteLine("\nFull name: {2} \n Section[{1}]Type: {0}", tipo, sezione.SectionName, fullName);
//If tipo is null, it means that the class doesn't exist
//So continue to next section
if (tipo == null)
{
Console.WriteLine("tipo null");
continue;
}
//If class exist, i get his properties
var elencoProprietà = tipo.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
//read all keys
foreach (var chiave in sezione.Keys)
{
Console.WriteLine("Key: " + chiave.KeyName + " Size property list: " + elencoProprietà.Count());
var proprietà = elencoProprietà.FirstOrDefault(p => p.Name.Equals(chiave.KeyName, StringComparison.InvariantCultureIgnoreCase));
//This property doesn't exist
if (proprietà == null)
{
Console.WriteLine("Property is null. " );
continue;
}
//Set the value to the class
var valore = Convert.ChangeType(chiave.Value, proprietà.PropertyType);
proprietà.SetValue(null, valore, null);
Console.WriteLine("Value: {0}", valore);
}
}
Console.ReadLine();
}
}
public static class Predefiniti_DataBase
{
public static string userId;
public static string psw;
public static string path;
}
}