« Custom Date Format Functions in SQL Server | Main | Anatomy of a ProgressBar for ASP.NET »

Friday, March 11, 2005

Read an INI File with C# (Managed)

Note: Code is .NET 1.1

When deploying Console or Windows Service applications, I use InstallShield which comes with this nice simple feature of dynamically creating INI files during install. Although .NET applications can utilize an app.config file very easily - sometimes an INI file is what you have to work with.

Following is a simple Console application to demonstrate reading an *.ini file, and assigning the keywords from each section to some private fields. These fields can be used during the operation of your application.

Here's the INI file and code.

[APPLICATIONINFO]
APPNAME=Hello World!
STARTVALUE=3
[LOCATIONS]
INSTALLDIR=C:\Program Files\My Program
DATABASEDIR=C:\Program Files\My Program\My Data

using System;
using System.IO;

namespace DemoINIFileReading
{
    ///
    /// Assign the INI keywords to fields, but not much else.
    ///
    class DemoReading
    {

        private string ini_APPNAME = null;
        private byte ini_STARTVALUE = 0;
        private string ini_INSTALLDIR = null;
        private string ini_DATABASEDIR = null;

        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main(string[] args)
        {
            // prepare myself
            DemoReading demo = new DemoReading();
            // read my ini file
            demo.read_ini_settings();
            // do my stuff
            Environment.ExitCode = demo.run_application();
        }

        private void read_ini_settings(){
            // get the configuration file
            FileInfo config_file = new FileInfo(String.Format("{0}\\DemoFile.ini", Directory.GetCurrentDirectory()));
            if(config_file.Exists){
                // read configuration values
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using(StreamReader stream_reader = new StreamReader(config_file.FullName)) {
                    string section = "[]";
                    string line;
                    // Read lines from the file until the end of
                    // the file is reached.
                    while((line = stream_reader.ReadLine()) != null){
                        // set the current section name
                        if(line.StartsWith("[") && line.EndsWith("]") && line != section){
                            section = line.ToUpper();
                        }
                        if(section == "[APPLICATIONINFO]"){
                            // assign keywords from this section
                            if(line.ToUpper().StartsWith("APPNAME=") && line.Length > 8){
                                ini_APPNAME = line.Substring(8);
                            }else if(line.ToUpper().StartsWith("STARTVALUE=") && line.Length > 11){
                                ini_STARTVALUE = byte.Parse(line.Substring(11));
                            }

                        }else if(section == "[LOCATIONS]"){
                            // assign keywords from this section
                            if(line.ToUpper().StartsWith("INSTALLDIR=") && line.Length > 11){
                                ini_INSTALLDIR = line.Substring(11);
                            }else if(line.ToUpper().StartsWith("DATABASEDIR=") && line.Length > 12){
                                ini_DATABASEDIR = line.Substring(12);
                            }
                        }
                    }
                }
            }else{
                throw new Exception("My INI file is missing.");
            }
        }

        private int run_application(){
            // do stuff here
            // and utilize my ini settings
            Console.Write(ini_APPNAME);
            return 1;
        }
    }
}

I find I do this quite often. I hope this is useful.

DemoINIFileReading.zip

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/1084389/6154331

Listed below are links to weblogs that reference Read an INI File with C# (Managed):

Comments

hye...its useful for me,thanks but how's the code for writing in existing INI file?

hi
I want to write the code which will check the config file and ini file.compare it and if there is any missing session then take it from ini file
can you give me sample code for that?
I want to first Read config file and then I want to compare it with .ini file.
if any secession missing then just copy it from ini file and paste it config file
reply please

thanks and regards
ajit

hello,
this is a nice article and hepls me out as i have never used ini files.But sir i would like to know the link between resource files and ini files in C# .net project. If u could help me out I'll be greatly indebted to u. Thanks once again.
thanks and regards
shraddha

Hi Shradda, there is no direct link.

Typically an INI file is a design choice for an application or process, for convenience of configuration, so you have to build the link yourself.

I hope that answers your question.

Scott,

Post a comment

If you have a TypeKey or TypePad account, please Sign In

Programmer for Hire

  • About Hiring Me:
  • Contact Information:
    • Name: P. Scott Cadillac
    • Phone: (902) 624-1266
    • Email: scott@xmlx.net
    • Location: Mahone Bay, Nova Scotia Canada
    • Timezone: Atlantic, ADT
  • Special Links: