C#中对ini文件的操作。

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace LX7.CLX7ClsLib
{
 /// <summary>
 /// Create a New INI file to store or load data
 /// </summary>
 public class CLX7IniFile
 {
  private static string m_Path;

  [DllImport("kernel32.dll")]
  private static extern long WritePrivateProfileString( string section
               , string key
               , string val
               , string filePath);

  [DllImport("kernel32.dll")]
  private static extern int GetPrivateProfileString( string   section
              , string   key
              , string   def
              , StringBuilder retVal
              , int    size
              , string   filePath);

  [DllImport("kernel32.dll")]
  static extern int GetPrivateProfileSection( string lpAppName
            , IntPtr lpReturnedString
            , int  nSize
            , string lpFileName);

  [DllImport("kernel32.dll")]
  private static extern int GetPrivateProfileSectionNames(IntPtr lpReturnedString
               , int  nSize
               , string lpFileName);

  private struct INI_INFO
  {
   public string   sSecName;
   public CLX7Collections oKeyName;
   public CLX7Collections oKeyValue;
  }

  private static INI_INFO[] m_Ini_Info;

  /// <summary>
  /// INIFile Constructor.
  /// </summary>
  /// <PARAM name="INIPath"></PARAM>
  public CLX7IniFile()
  {
  }

  #region プロパティ
  //
  // iniファイルフルパス
  //
  public static string Path
  {
   set
   {
    m_Path = value;
   }
   get
   {
    return m_Path;
   }
  }
  #endregion

  #region メソッド
  /// <summary>
  /// iniファイルを読み込む
  /// </summary>
  /// <returns>true:成功、false:失敗</returns>
  public static bool IniReadAllParam()
  {

   string[] sArySecNames;
   string[] sAryKeyNames;
   int   i;
   int   j;

   // ファイルが存在するか
   if (m_Path == null)
   {
    MessageBox.Show("INIファイルパスが指定されていません。","INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    return false;
   }
   if (!System.IO.File.Exists(m_Path))
   {
    MessageBox.Show("INIファイルが存在しません。(" + m_Path + ")","INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    return false;
   }

   try
   {

    // 全てのセクションを取得
    if (!GetPrivateProfileSectionNamesEx(out sArySecNames))
    {
     MessageBox.Show("セクションの取得に失敗しました。","INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
     return false;
    }

    m_Ini_Info = new INI_INFO[sArySecNames.Length];

    for (i=0;i<sArySecNames.Length;i++)
    {
     sAryKeyNames = null;

     // 全てのキーを取得
     if (!GetPrivateProfileSectionEx(sArySecNames[i],out sAryKeyNames))
     {
      MessageBox.Show("キーの取得に失敗しました。","INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
      return false;
     }

     m_Ini_Info[i].sSecName = sArySecNames[i];
     m_Ini_Info[i].oKeyName = new CLX7Collections();
     m_Ini_Info[i].oKeyValue = new CLX7Collections();

     for (j=0;j<sAryKeyNames.Length;j++)
     {
      m_Ini_Info[i].oKeyName.Add(sAryKeyNames[j].Split('=')[0]);
      m_Ini_Info[i].oKeyValue.Add(sAryKeyNames[j].Split('=')[1]);
     }
    }
 
//    for (i=0;i<m_Ini_Info.Length;i++)
//    {
//     for (j=0;j<m_Ini_Info[i].oKeyName.Count;j++)
//     {
//      Console.WriteLine(m_Ini_Info[i].sSecName + ":" + m_Ini_Info[i].oKeyName[j].ToString() + "=" + m_Ini_Info[i].oKeyValue[j].ToString());
//     }
//    }

   }
   catch (Exception ex)
   {
    MessageBox.Show("INIファイル読込処理において実行時エラーが発生しました。\r\n" + ex.Message,"INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    return false;
   }

   return true;

  }
  /// <summary>
  /// iniファイルからデータを取得する。
  /// </summary>
  /// <param name="asSection">セクション名</param>
  /// <param name="asKey">キー名</param>
  /// <returns>データ値</returns>
  public static string IniGetValue(string asSection, string asKey)
  {
   int i;
   int j;

   try
   { 
    for (i=0;i<m_Ini_Info.Length;i++)
    {
     if (m_Ini_Info[i].sSecName.ToUpper() == asSection.ToUpper())
     {
      for (j=0;j<m_Ini_Info[i].oKeyName.Count;j++)
      {
       if (m_Ini_Info[i].oKeyName[j].ToString().ToUpper() == asKey.ToUpper())
       {
        return m_Ini_Info[i].oKeyValue[j].ToString();
       }
      }
     }
    }
   }
   catch
   {
   }

   return "";

  }
  /// <summary>
  /// iniファイルにデータをセットする。
  /// </summary>
  /// <PARAM name="Section"></PARAM>
  /// セクション名
  /// <PARAM name="Key"></PARAM>
  /// キー名
  /// <PARAM name="Value"></PARAM>
  /// データ値
  public static void IniSetValue(string Section,string Key,string Value)
  {
   try
   {
    WritePrivateProfileString(Section.ToUpper(),Key.ToUpper(),Value,m_Path);
   }
   catch
   {
   }
   
  }
  #endregion

  private static bool GetPrivateProfileSectionNamesEx(out string[] section)
  {
   byte[] bBuff;
   int  MAX_BUFFER = 32767;

   section = null;

   try
   {
    // メモリ割当
    IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);

    int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, m_Path);

    // 取得失敗
    if ((bytesReturned == MAX_BUFFER - 2) ||(bytesReturned == 0))
    {
     return false;
    }

    bBuff = new byte[bytesReturned-1];

    // ポインタを参照し、データを取得
    for (int i = 0; i < bytesReturned-1; i++)
    {
     bBuff[i] = Marshal.ReadByte(new IntPtr((int)pReturnedString + (int)i));
    }

    // メモリ解放
    Marshal.FreeCoTaskMem(pReturnedString);

    section = System.Text.Encoding.GetEncoding("Shift_JIS").GetString(bBuff).Split('\0');
   }
   catch (Exception ex)
   {
    MessageBox.Show("INIファイル読込処理において実行時エラーが発生しました。\r\n" + ex.Message,"INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    return false;
   }

   return true;

  }

  private static bool GetPrivateProfileSectionEx(string appName, out string[] section)
  {
   byte[] bBuff;
   int  MAX_BUFFER = 32767;

   section = null;

   try
   {

    // メモリ割当
    IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);

    int bytesReturned = GetPrivateProfileSection(appName, pReturnedString, MAX_BUFFER, m_Path);

    // 取得失敗
    if ((bytesReturned == MAX_BUFFER - 2) ||(bytesReturned == 0))
     return false;

    bBuff = new byte[bytesReturned-1];

    // ポインタを参照し、データを取得
    for (int i = 0; i < bytesReturned-1; i++)
    {
     bBuff[i] = Marshal.ReadByte(new IntPtr((int)pReturnedString + (int)i));
    }

    // メモリ解放
    Marshal.FreeCoTaskMem(pReturnedString);

    section = System.Text.Encoding.GetEncoding("Shift_JIS").GetString(bBuff).Split('\0');

   }
   catch (Exception ex)
   {
    MessageBox.Show("INIファイル読込処理において実行時エラーが発生しました。\r\n" + ex.Message,"INIファイル読込エラー",MessageBoxButtons.OK,MessageBoxIcon.Warning);
    return false;
   }

   return true;
  }
       
  /// <summary>
  /// Read Data Value From the Ini File
  /// </summary>
  /// <PARAM name="Section"></PARAM>
  /// <PARAM name="Key"></PARAM>
  /// <PARAM name="Path"></PARAM>
  /// <returns></returns>
  private static string IniReadValue(string Section,string Key)
  {
   StringBuilder temp = new StringBuilder(255);

   try
   {
    int i = GetPrivateProfileString(Section,Key,"",temp, 255, m_Path);
   }
   catch
   {
   }
   return temp.ToString();
  }

 }
}

posted @ 2006-08-24 12:39  糊涂小猪  阅读(1252)  评论(0编辑  收藏  举报