dotFusion.net

Multi-platform .INI files in C#

Posted on: January 29th, 2009.
Category: C#

Here is a new way of reading and writing .ini files in C#.
 

It’s an alternative INI file parser written by me. It uses Regex and Collections. I’m only posting a part of the source code because it is too long. But if you scroll a little bit you can download the full source with a Demo project included.
 

Please redistribute and modify under the terms of GNU LGPL v3.0.

 
Source code:

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
 
namespace MPIniReadWrite
{
    class MultiplatformIni
    {
        private String iniFilePath;
        public String IniPath
        {
            get { return iniFilePath; }
        }
        private static Char decSep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.ToCharArray()[0];
        private static Regex keyValRegex = new Regex(
          @"((\s)*(?<Key>([^\=^\n]+))[\s^\n]*\=(\s)*(?<Value>([^\n]+(\n){0,1})))",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | 
            RegexOptions.CultureInvariant
        );
        private static Regex secRegex = new Regex(
          @"(\[)*(?<Section>([^\]^\n]+))(\])" ,
          RegexOptions.Compiled | RegexOptions.CultureInvariant
        );
 
        private ArrayList newValues = new ArrayList();
        struct sectKeyVal
        {
            public String section, key, value;
            public sectKeyVal(String section, String key, String value)
            {
                this.section = section;
                this.key = key;
                this.value = value;
            }
        }
 
        public MultiplatformIni(String iniFilePath)
        {
            this.iniFilePath = iniFilePath;
        }
        ~MultiplatformIni()
        {
            Flush();
        }
// Source code truncated...

 
Download the full source code and an example (Visual C# 2005 Express Project)

I’ve compiled this using .NET framework 2.0 and Mono 2.2 with no problem. Have fun! :)

INI files manipulation using C#

Posted on: January 26th, 2009.
Category: C#

This time I’m going to present you the Windows way of Reading and Writing .INI files using C#.
 

This is far from the best way of doing this, because it works only when your executable is being run on Windows (this code uses kernel32.dll functions). Here is the base INI Read/Write class code:

 
Here’s the nuberings remover source:

using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace IniReadWrite
{
    class IniFile
    {
        [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,
          string key, string value, string iniFilePath);
        [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,
          string key, string defValue, StringBuilder retValue, int size, string iniFilePath);
 
        private const int valueLength = 255; // Maximum length of value
        private String iniPath; // The path of our .ini file
 
        public IniFile(String iniFilePath)
        {
            iniPath = iniFilePath;
        }
 
        public void WriteString(String section, String key, String value)
        {
            WritePrivateProfileString(section, key, value, iniPath);
        }
        public void WriteInt(String section, String key, int value)
        {
            WriteString(section, key, value.ToString());
        }
        public void WriteDouble(String section, String key, Double value)
        {
            WriteString(section, key, value.ToString());
        }
 
        public String ReadString(String section, String key, String defValue)
        {
            StringBuilder tmp = new StringBuilder(valueLength);
            int i = GetPrivateProfileString(section, key, defValue, tmp, valueLength, iniPath);
 
            return tmp.ToString();
        }
        public int ReadInt(String section, String key, int defValue)
        {
            return Int32.Parse(ReadString(section, key, defValue.ToString()));
        }
        public Double ReadDouble(String section, String key, Double defValue)
        {
            return Double.Parse(ReadString(section, key, defValue.ToString()));
        }
    }
}

 
Download this code and an example (Visual C# 2005 Express Edition Project)

I will soon be posting a version of this code that doesn’t need kernel32.dll and should work cross-platform even when compiled for Linux (using Mono).

A Simple Morse Code Converter

Posted on: January 18th, 2009.
Category: C#

Hello everybody, yesterday I wrote for you a simple Morse code to Text & Text to Morse code converter.
 

It’s 100% Morse code compliant and it supports only numbers, letters and space.
As you may already know the official Morse code specification does not provide symbols for any special characters (?.!=+- for example). But if you are interested – write me a line and I may add some of them to the next version of the example program.

 

Source code:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace MorseCodeConverter
{
    class MorseCodeCore
    {
        private Char[] Letters = new Char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g',
          'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
          'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
          '9', ' '};
        private String[] MorseCode = new String[] {".-", "-...", "-.-.",
          "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", 
          "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", 
          "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", 
          "...--", "....-", ".....", "-....", "--...", "---..", "----.", " "};
 
        public String ConvertTextToMorse(String text)
        {
            text = text.ToLower();
            String result = "";
            int index = -1;
            for (int i = 0; i <= text.Length - 1; i++)
            {
                index = Array.IndexOf(Letters, text[i]);
                if (index != -1)
                    result += MorseCode[index] + " ";
            }
 
            return result;
        }
 
        public String ConvertMorseToText(String text)
        {
            text = "@" + text.Replace(" ", "@@") + "@";
            int index = -1;
            foreach (Char c in Letters)
            {
                index = Array.IndexOf(Letters, c);
                text = text.Replace("@" + MorseCode[index] + "@", "@" + c.ToString() + "@");
            }
 
            return text.Replace("@@@@", " ").Replace("@", "");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            MorseCodeCore Morse = new MorseCodeCore();
 
            Console.WriteLine("Converting from text to morse: ");
            String str = Morse.ConvertTextToMorse("string to convert to morse code") ;
            Console.WriteLine(str);
 
            Console.WriteLine("\nConverting from morse to text: ");
            str = Morse.ConvertMorseToText("... - .-. .. -. --.   - ---   -.-." + 
              " --- -. ...- . .-. -   -... .- -.-. -.-   - ---   - . -..- -");
            Console.WriteLine(str);
 
            Console.ReadKey();
        }
    }
}

 
Download the example Source Code (MS Visual C# Express Edition Project)

This is a really simple example. If you think of a more sophisticated one, you may send it to me, and I will publish it with your name and email/website…