Parse the key-value properties file
By Perry
This program can be used to parse the properties file which has the format of key-value pair. This program will separate keys and values into different array lists.
Complete C# program:
----------------------
using System;
using System.Collections;
using System.Text;
using System.IO;
namespace ReadFileTest
{
class Program
{
static void Main(string[] args)
{
int x = 0;
string line = null;
ArrayList value = new ArrayList();
ArrayList key = new ArrayList();
char[] spaces = { ' ', '\t' };
string propertyFilePath = @"C:\\local\\properties.txt";
if (File.Exists(propertyFilePath))
{
StreamReader streamReader = new StreamReader(propertyFilePath);
streamReader = new StreamReader(propertyFilePath);
line = streamReader.ReadLine();
while (line != null)
{
line = line.Trim();
if (!(line == string.Empty || line.IndexOfAny(spaces) < 0))
{
key.Add(line.Substring(0, line.IndexOfAny(spaces)).Trim());
value.Add(line.Substring(line.IndexOfAny(spaces)).Trim());
}
line = streamReader.ReadLine();
}
}
else
throw new Exception("Properties File not Found. Please install");
for (x = 0; x < key.Count; x++)
System.Console.WriteLine(key[x] + "-->" + value[x]);
Console.Read();
}
}
}
Example file: Key value can be separated by any number of spaces
-------------------------------------------------------------------
abc xyz
abc2 pqr
abc3 pqr3
xyz2 lkj
Output of program:
-------------------
abc-->xyz
abc2-->pqr
abc3-->pqr3
xyz2-->lkj
Regards,
Megha
Popularity (1355 Views)