[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 610
  • Last Modified:

How to read a property file in C#?

How to read a property file in C#?

I have a file which contains key=value pairs, one in each line.

I want to get the value for a particular key.

0
rajesh_khater
Asked:
rajesh_khater
  • 5
  • 4
  • 2
  • +1
2 Solutions
 
sabeeshCommented:
Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, "Two");

            foreach (object key in ht.Keys)
            {
               string value = ht[key].ToString();
            }
0
 
rajesh_khaterAuthor Commented:
But how to load the hashtable from the file?
0
 
sabeeshCommented:
You have to read the file line by line and put it into a hashtable.
string[] arr = File.ReadAllLines(@"C:\DBScript.txt");
and some logic to separate your key value pair
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Bob LearnedCommented:
Are you talking about an .ini file (GetPrivateProfileString, et al)?

Bob
0
 
rajesh_khaterAuthor Commented:
Even an ini file will do.
0
 
Bob LearnedCommented:
Try this:

using System;
using System.Runtime.InteropServices;

public class IniFileReaderWriter
{
    [DllImport("kernel32", EntryPoint = "WritePrivateProfileStringW", CharSet = CharSet.Unicode,
        SetLastError = true, ExactSpelling = true)]
    private static extern int WritePrivateProfileString(string lpApplicationName,
        string lpKeyName, string lpString, string lpFileName);

    [DllImport("kernel32", EntryPoint = "GetPrivateProfileStringW", CharSet = CharSet.Unicode,
        SetLastError = true, ExactSpelling = true)]
    private static extern int GetPrivateProfileString(string lpApplicationName,
        string lpKeyName, string lpDefault, string lpReturnedString, int nSize, string lpFileName);

    public static string INIRead(string INIPath, string SectionName, string KeyName, string DefaultValue)
    {

        // Allocate some room.
        string sData = new string(' ', 1024);
        int n = GetPrivateProfileString(SectionName, KeyName, DefaultValue, sData, sData.Length, INIPath);

        if (n > 0)
        {
            // return whatever it gave us
            return sData.Substring(0, n);
        }
        else
        {
            return "";
        }
    }

    public static string INIRead(string INIPath, string SectionName, string KeyName)
    {

        // Overload 1 assumes zero-length default
        return INIRead(INIPath, SectionName, KeyName, "");

    }

    public static string INIRead(string INIPath, string SectionName)
    {

        // Overload 2 returns all keys in a given section of the given file
        return INIRead(INIPath, SectionName, null, "");

    }

    public static string INIRead(string INIPath)
    {
        // Overload 3 returns all section names given just path
        return INIRead(INIPath, null, null, "");
    }

    public static void INIWrite(string INIPath, string SectionName, string KeyName, string TheValue)
    {

        WritePrivateProfileString(SectionName, KeyName, TheValue, INIPath);

    }

    public static void INIDelete(string INIPath, string SectionName, string KeyName)
    {
        // delete single line from section

        WritePrivateProfileString(SectionName, KeyName, null, INIPath);

    }

    public static void INIDelete(string INIPath, string SectionName)
    {
        // Delete section from INI file
        WritePrivateProfileString(SectionName, null, null, INIPath);
    }

}

Bob
0
 
rajesh_khaterAuthor Commented:
Thanks. That will help. Meanwhile, can you show me some code to fill up a HashTable or a StringDictionary or a NameValueCollection given a property file path?
0
 
Bob LearnedCommented:
Can you show me what the file looks like?

Bob
0
 
rajesh_khaterAuthor Commented:
key1=value1
key2=value2
key3=value3

There may be blank lines in between.
0
 
Bob LearnedCommented:
Try this:

        private StringDictionary ReadFile(string fileName)
        {
            string[] lines = File.ReadAllLines(fileName);

            StringDictionary dictionary = new StringDictionary();

            foreach (string entry in lines)
            {
                if (entry.Trim().Length > 0)
                {
                    string[] parts = entry.Split('=');

                    if (parts.Length == 2)
                        dictionary.Add(parts[0], parts[1]);
                }
            }
            return dictionary;
        }

Bob
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
* Just a minor note...

If there is a possibility that a key value might be duplicated in your file, then you need to either:
(1) Check for the existence of the key in the StringDictionary first
(2) Place the Add() call in a Try/Catch block
(3) Switch to using d.Item[x] = y instead  (this would keep the newest value)
0
 
Bob LearnedCommented:
Hey, Shadow, how's it going?

Bob
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Who knows what evil lurks in the hearts of men? The Shadow knows!...  ;)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now