65.9K
CodeProject is changing. Read more.
Home

Load config files

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (8 votes)

Sep 6, 2006

LGPL3
viewsIcon

35178

Load an ini file to configure own application

Introduction

this class is to read ini files

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace touzasClass
{
    public static class config{
        public static string ruta = System.Windows.Forms.Application.StartupPath + @"\config.ini";
        public static IniFile ini = new IniFile(ruta);

        public static string getKeyValue(string section, string key){
            string tmp = String.Empty;
            tmp = ini.IniReadValue(section, key);
            return tmp;
        }
    }

    public class IniFile {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key,string val,string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
            string key,string def, StringBuilder retVal, int size,string filePath);

        public IniFile(string INIPath) {
            path = INIPath;
        }
        public void IniWriteValue(string Section,string Key,string Value) {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }
        
        public string IniReadValue(string Section,string Key) {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 255, this.path);
            return temp.ToString();

        }
    }
}
=============================================================================================
==================================== SAMPLE  ============================================
=============================================================================================

string server = string.empty;
server = config.getKeyValue("Configuracion", "SERVIDOR")
--- RESULT ---
server = "localhost"

=============================================================================================
==================================== ARCHIVO config.ini ============================================
=============================================================================================

[Configuracion]
SERVIDOR = localhost
DATABASE = dbPruebas
USUARIO = userdb
CLAVE = pwd