Web Design that taps into the haromny and vision of your dreams.

Reading and Writing INI Files with C#

How to use INI files in C#

Written By on in C#

123 words, estimated reading time 1 minutes.

This short snippet is another tool in my utility class. You can use it to quickly read and write settings from an old school INI configuration file. Yes I still use INI files!

using System;
using System.Runtime.InteropServices;
using System.Text;
 
public static class IniFile
{
  [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 static void WriteValue(string path, string Section, string Key, string Value)
  {
    WritePrivateProfileString(Section, Key, Value, path);
  }
 
  public static string ReadValue(string path, string Section, string Key)
  {
    StringBuilder temp = new StringBuilder(255);
    int i = GetPrivateProfileString(Section, Key, "", temp, 255, path);
    return temp.ToString();
  }
}

Usage is very simple, simply call IniFile.WriteValue or IniFile.ReadValue with the full path to the INI file, the section name and the configuration key.

Last updated on: Wednesday 21st June 2017

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me