C Ini file operation instance

  • 2020-06-12 10:31:44
  • OfStack

ini file operation seen in open source China, written not read, save for later use


using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
namespace wuyisky{
  /**//**/
  /**//// <summary>
  /// IniFiles The class of 
  /// </summary>
  public class IniFiles
  {
    public string FileName; //INI The file name 
    // Read and write a statement INI Of the file API function 
    [DllImport("kernel32")]
    private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
    // Class constructor, pass INI The file name 
    public IniFiles(string AFileName)
    {
      //  Determine if the file exists 
      FileInfo fileInfo = new FileInfo(AFileName);
      //Todo: Find out how to use enumerations 
      if ((!fileInfo.Exists))
      { //|| (FileAttributes.Directory in fileInfo.Attributes))
        // File does not exist, create file 
        System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
        try
        {
          sw.Write("# Form profile ");
          sw.Close();
        }
        catch
        {
          throw (new ApplicationException("Ini File does not exist "));
        }
      }
      // It must be a complete path, not a relative path 
      FileName = fileInfo.FullName;
    }
    // write INI file 
    public void WriteString(string Section, string Ident, string Value)
    {
      if (!WritePrivateProfileString(Section, Ident, Value, FileName))
      {
 
        throw (new ApplicationException(" write Ini File error "));
      }
    }
    // read INI The file specified 
    public string ReadString(string Section, string Ident, string Default)
    {
      Byte[] Buffer = new Byte[65535];
      int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
      // Must be set 0 (the default code page of the system), otherwise Chinese cannot be supported 
      string s = Encoding.GetEncoding(0).GetString(Buffer);
      s = s.Substring(0, bufLen);
      return s.Trim();
    }
    // Read an integer 
    public int ReadInteger(string Section, string Ident, int Default)
    {
      string intStr = ReadString(Section, Ident, Convert.ToString(Default));
      try
      {
        return Convert.ToInt32(intStr);
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        return Default;
      }
    }
    // Write an integer 
    public void WriteInteger(string Section, string Ident, int Value)
    {
      WriteString(Section, Ident, Value.ToString());
    }
    // Read the Boolean 
    public bool ReadBool(string Section, string Ident, bool Default)
    {
      try
      {
        return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        return Default;
      }
    }
    // write Bool
    public void WriteBool(string Section, string Ident, bool Value)
    {
      WriteString(Section, Ident, Convert.ToString(Value));
    }
    // from Ini File, will be specified Section All of the names Ident Add to the list 
    public void ReadSection(string Section, StringCollection Idents)
    {
      Byte[] Buffer = new Byte[16384];
      //Idents.Clear();
      int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
       FileName);
      // right Section parsing 
      GetStringsFromBuffer(Buffer, bufLen, Idents);
    }
    private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
    {
      Strings.Clear();
      if (bufLen != 0)
      {
        int start = 0;
        for (int i = 0; i < bufLen; i++)
        {
          if ((Buffer[i] == 0) && ((i - start) > 0))
          {
            String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
            Strings.Add(s);
            start = i + 1;
          }
        }
      }
    }
    // from Ini File, read all of them Sections The name of the 
    public void ReadSections(StringCollection SectionList)
    {
      //Note: Must use Bytes To do this, StringBuilder I'm only going to get the first one 1 a Section
      byte[] Buffer = new byte[65535];
      int bufLen = 0;
      bufLen = GetPrivateProfileString(null, null, null, Buffer,
       Buffer.GetUpperBound(0), FileName);
      GetStringsFromBuffer(Buffer, bufLen, SectionList);
    }
    // Read the specified Section All of the Value To the list 
    public void ReadSectionValues(string Section, NameValueCollection Values)
    {
      StringCollection KeyList = new StringCollection();
      ReadSection(Section, KeyList);
      Values.Clear();
      foreach (string key in KeyList)
      {
        Values.Add(key, ReadString(Section, key, ""));
  
      }
    }
    /**///// Read the specified Section All of the Value Go to the list, 
    //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
    //{  string sectionValue;
    //  string[] sectionValueSplit;
    //  StringCollection KeyList = new StringCollection();
    //  ReadSection(Section, KeyList);
    //  Values.Clear();
    //  foreach (string key in KeyList)
    //  {
    //    sectionValue=ReadString(Section, key, "");
    //    sectionValueSplit=sectionValue.Split(splitString);
    //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
 
    //  }
    //}
    // Remove a Section
    public void EraseSection(string Section)
    {
      //
      if (!WritePrivateProfileString(Section, null, null, FileName))
      {
        throw (new ApplicationException(" Unable to remove Ini In the file Section"));
      }
    }
    // Delete a Section The key 
    public void DeleteKey(string Section, string Ident)
    {
      WritePrivateProfileString(Section, Ident, null, FileName);
    }
    //Note: for Win9X , which needs to be implemented UpdateFile Method writes the data in the buffer to a file 
    // in Win NT, 2000 and XP On, are written directly to the file, no buffer, so, no need to implement UpdateFile
    // Performed on Ini This method should be called to update the buffer after the file has been modified. 
    public void UpdateFile()
    {
      WritePrivateProfileString(null, null, null, FileName);
    }
    // Check a Section Whether a key value below exists 
    public bool ValueExists(string Section, string Ident)
    {
      //
      StringCollection Idents = new StringCollection();
      ReadSection(Section, Idents);
      return Idents.IndexOf(Ident) > -1;
    }
    // Ensure the release of resources 
    ~IniFiles()
    {
      UpdateFile();
    }
  }
}


Related articles: