123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- namespace BaseLibRWFile
- {
- public class Ini
- {
- public const int MaxSectionSize = 32767; // 32 KB
- private string m_path;
- private Dictionary<string, object> _locks = new Dictionary<string, object>();
- #region P/Invoke declares
- [System.Security.SuppressUnmanagedCodeSecurity]
- private static class NativeMethods
- {
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
- uint nSize,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern uint GetPrivateProfileString(string lpAppName,
- string lpKeyName,
- string lpDefault,
- StringBuilder lpReturnedString,
- int nSize,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern uint GetPrivateProfileString(string lpAppName,
- string lpKeyName,
- string lpDefault,
- [In, Out] char[] lpReturnedString,
- int nSize,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern int GetPrivateProfileString(string lpAppName,
- string lpKeyName,
- string lpDefault,
- IntPtr lpReturnedString,
- uint nSize,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern int GetPrivateProfileInt(string lpAppName,
- string lpKeyName,
- int lpDefault,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- public static extern int GetPrivateProfileSection(string lpAppName,
- IntPtr lpReturnedString,
- uint nSize,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool WritePrivateProfileString(string lpAppName,
- string lpKeyName,
- string lpString,
- string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool WritePrivateProfileSection(string lpAppName,
- string lpstring,
- string lpFileName);
- }
- #endregion
- /// <summary>
- /// 实例化Ini
- /// </summary>
- /// <param name="path">ini文件完整路径</param>
- /// <returns></returns>
- public Ini(string path)
- {
- m_path = System.IO.Path.GetFullPath(path);
- if (!_locks.ContainsKey(m_path))
- {
- _locks.Add(m_path, new object());
- }
- }
- /// <summary>
- /// 读取ini文件指定数据
- /// </summary>
- /// <param name="label">数据标签</param>
- /// <param name="name">数据名称</param>
- /// <param name="value">默认值</param>
- /// <returns></returns>
- public string ReadIni(string label, string name, String value) //读配置文件
- {
- try
- {
- string ret;
- ret = GetString(label, name, value);
- if (ret == value)
- {
- WriteValue(label, name, value);
- }
- return ret;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString(), "ReadIni Error");
- return null;
- }
- }
- /// <summary>
- /// 写入数据到ini文件
- /// </summary>
- /// <param name="label">数据标签</param>
- /// <param name="name">数据名称</param>
- /// <param name="value">要写入的值</param>
- /// <returns></returns>
- public void WriteIni(string label, string name, String value) //写配置文件
- {
- try
- {
- WriteValue(label, name, value);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString(), "WriteIni Error");
- }
- }
- public string Path
- {
- get
- {
- return m_path;
- }
- }
- /// <summary>
- /// 创建文件夹
- /// </summary>
- /// <param name="DirectoryFileName">文件夹完整路径</param>
- /// <returns></returns>
- public void DirectoryCreate(string DirectoryFileName)
- {
- if (!Directory.Exists(DirectoryFileName))
- {
- Directory.CreateDirectory(DirectoryFileName);
- }
- }
- /// <summary>
- /// 创建ini文件
- /// </summary>
- /// <param name="FileName">ini文件完整路径</param>
- /// <returns></returns>
- public void CreateFile(string FileName)
- {
- if (!(File.Exists(FileName)))
- {
- File.Create(FileName).Close();
- }
- }
- public void CopyFile(string strSourcePath, string strTargetPath, bool IsCoverage)
- {
- try
- {
- if (!File.Exists(strTargetPath))
- {
- CreateFile(strTargetPath);
- }
- File.Copy(strSourcePath, strTargetPath, IsCoverage);
- }
- catch
- { }
- }
- #region Get Value Methods
- public string GetString(string sectionName,
- string keyName,
- string defaultValue)
- {
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- if (keyName == null)
- throw new ArgumentNullException(nameof(keyName));
- lock (_locks[m_path])
- {
- StringBuilder retval = new StringBuilder(Ini.MaxSectionSize);
- NativeMethods.GetPrivateProfileString(sectionName,
- keyName,
- defaultValue,
- retval,
- Ini.MaxSectionSize,
- m_path);
- return retval.ToString();
- }
- }
- /// <summary>
- /// Gets the value of a setting in an ini file as a <see cref="T:System.Int16"/>.
- /// </summary>
- /// <param name="sectionName">The name of the section to read from.</param>
- /// <param name="keyName">The name of the key in section to read.</param>
- /// <param name="defaultValue">The default value to return if the key
- /// cannot be found.</param>
- /// <returns>The value of the key, if found. Otherwise, returns
- /// <paramref name="defaultValue"/>.</returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public int GetInt16(string sectionName,
- string keyName,
- short defaultValue)
- {
- int retval = GetInt32(sectionName, keyName, defaultValue);
- return Convert.ToInt16(retval);
- }
- /// <summary>
- /// Gets the value of a setting in an ini file as a <see cref="T:System.Int32"/>.
- /// </summary>
- /// <param name="sectionName">The name of the section to read from.</param>
- /// <param name="keyName">The name of the key in section to read.</param>
- /// <param name="defaultValue">The default value to return if the key
- /// cannot be found.</param>
- /// <returns>The value of the key, if found. Otherwise, returns
- /// <paramref name="defaultValue"/></returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public int GetInt32(string sectionName,
- string keyName,
- int defaultValue)
- {
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- if (keyName == null)
- throw new ArgumentNullException(nameof(keyName));
- lock (_locks[m_path])
- {
- return NativeMethods.GetPrivateProfileInt(sectionName, keyName, defaultValue, m_path);
- }
- }
- /// <summary>
- /// Gets the value of a setting in an ini file as a <see cref="T:System.Double"/>.
- /// </summary>
- /// <param name="sectionName">The name of the section to read from.</param>
- /// <param name="keyName">The name of the key in section to read.</param>
- /// <param name="defaultValue">The default value to return if the key
- /// cannot be found.</param>
- /// <returns>The value of the key, if found. Otherwise, returns
- /// <paramref name="defaultValue"/></returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public double GetDouble(string sectionName,
- string keyName,
- double defaultValue)
- {
- string retval = GetString(sectionName, keyName, "");
- if (retval == null || retval.Length == 0)
- {
- return defaultValue;
- }
- return Convert.ToDouble(retval, CultureInfo.InvariantCulture);
- }
- #endregion
- #region GetSectionValues Methods
- /// <summary>
- /// Gets all of the values in a section as a list.
- /// </summary>
- /// <param name="sectionName">
- /// Name of the section to retrieve values from.
- /// </param>
- /// <returns>
- /// A <see cref="List{T}"/> containing <see cref="KeyValuePair{T1, T2}"/> objects
- /// that describe this section. Use this verison if a section may contain
- /// multiple items with the same key value. If you know that a section
- /// cannot contain multiple values with the same key name or you don't
- /// care about the duplicates, use the more convenient
- /// <see cref="GetSectionValues"/> function.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> is a null reference (Nothing in VB)
- /// </exception>
- public List<KeyValuePair<string, string>> GetSectionValuesAsList(string sectionName)
- {
- List<KeyValuePair<string, string>> retval;
- string[] keyValuePairs;
- string key, value;
- int equalSignPos;
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- //Allocate a buffer for the returned section names.
- IntPtr ptr = Marshal.AllocCoTaskMem(Ini.MaxSectionSize);
- try
- {
- //Get the section key/value pairs into the buffer.
- lock (_locks[m_path])
- {
- int len = NativeMethods.GetPrivateProfileSection(sectionName,
- ptr,
- Ini.MaxSectionSize,
- m_path);
- keyValuePairs = ConvertNullSeperatedStringToStringArray(ptr, len);
- }
- }
- finally
- {
- //Free the buffer
- Marshal.FreeCoTaskMem(ptr);
- }
- //Parse keyValue pairs and add them to the list.
- retval = new List<KeyValuePair<string, string>>(keyValuePairs.Length);
- for (int i = 0; i < keyValuePairs.Length; ++i)
- {
- //Parse the "key=value" string into its constituent parts
- equalSignPos = keyValuePairs[i].IndexOf('=');
- key = keyValuePairs[i].Substring(0, equalSignPos);
- value = keyValuePairs[i].Substring(equalSignPos + 1,
- keyValuePairs[i].Length - equalSignPos - 1);
- retval.Add(new KeyValuePair<string, string>(key, value));
- }
- return retval;
- }
- /// <summary>
- /// Gets all of the values in a section as a dictionary.
- /// </summary>
- /// <param name="sectionName">
- /// Name of the section to retrieve values from.
- /// </param>
- /// <returns>
- /// A <see cref="Dictionary{T, T}"/> containing the key/value
- /// pairs found in this section.
- /// </returns>
- /// <remarks>
- /// If a section contains more than one key with the same name,
- /// this function only returns the first instance. If you need to
- /// get all key/value pairs within a section even when keys have the
- /// same name, use <see cref="GetSectionValuesAsList"/>.
- /// </remarks>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> is a null reference (Nothing in VB)
- /// </exception>
- public Dictionary<string, string> GetSectionValues(string sectionName)
- {
- List<KeyValuePair<string, string>> keyValuePairs;
- Dictionary<string, string> retval;
- keyValuePairs = GetSectionValuesAsList(sectionName);
- //Convert list into a dictionary.
- retval = new Dictionary<string, string>(keyValuePairs.Count);
- foreach (KeyValuePair<string, string> keyValuePair in keyValuePairs)
- {
- //Skip any key we have already seen.
- if (!retval.ContainsKey(keyValuePair.Key))
- {
- retval.Add(keyValuePair.Key, keyValuePair.Value);
- }
- }
- return retval;
- }
- #endregion
- #region Get Key/Section Names
- /// <summary>
- /// Gets the names of all keys under a specific section in the ini file.
- /// </summary>
- /// <param name="sectionName">
- /// The name of the section to read key names from.
- /// </param>
- /// <returns>An array of key names.</returns>
- /// <remarks>
- /// The total length of all key names in the section must be
- /// less than 32KB in length.
- /// </remarks>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> is a null reference (Nothing in VB)
- /// </exception>
- public string[] GetKeyNames(string sectionName)
- {
- int len;
- string[] retval;
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- //Allocate a buffer for the returned section names.
- IntPtr ptr = Marshal.AllocCoTaskMem(Ini.MaxSectionSize);
- try
- {
- //Get the section names into the buffer.
- lock (_locks[m_path])
- {
- len = NativeMethods.GetPrivateProfileString(sectionName,
- null,
- null,
- ptr,
- Ini.MaxSectionSize,
- m_path);
- retval = ConvertNullSeperatedStringToStringArray(ptr, len);
- }
- }
- finally
- {
- //Free the buffer
- Marshal.FreeCoTaskMem(ptr);
- }
- return retval;
- }
- /// <summary>
- /// Gets the names of all sections in the ini file.
- /// </summary>
- /// <returns>An array of section names.</returns>
- /// <remarks>
- /// The total length of all section names in the section must be
- /// less than 32KB in length.
- /// </remarks>
- public string[] GetSectionNames()
- {
- string[] retval;
- int len;
- //Allocate a buffer for the returned section names.
- IntPtr ptr = Marshal.AllocCoTaskMem(Ini.MaxSectionSize);
- try
- {
- //Get the section names into the buffer.
- lock (_locks[m_path])
- {
- len = NativeMethods.GetPrivateProfileSectionNames(ptr,
- Ini.MaxSectionSize, m_path);
- retval = ConvertNullSeperatedStringToStringArray(ptr, len);
- }
- }
- finally
- {
- //Free the buffer
- Marshal.FreeCoTaskMem(ptr);
- }
- return retval;
- }
- /// <summary>
- /// Converts the null seperated pointer to a string into a string array.
- /// </summary>
- /// <param name="ptr">A pointer to string data.</param>
- /// <param name="valLength">
- /// Length of the data pointed to by <paramref name="ptr"/>.
- /// </param>
- /// <returns>
- /// An array of strings; one for each null found in the array of characters pointed
- /// at by <paramref name="ptr"/>.
- /// </returns>
- private static string[] ConvertNullSeperatedStringToStringArray(IntPtr ptr, int valLength)
- {
- string[] retval;
- if (valLength == 0)
- {
- //Return an empty array.
- retval = Array.Empty<string>();
- }
- else
- {
- //Convert the buffer into a string. Decrease the length
- //by 1 so that we remove the second null off the end.
- string buff = Marshal.PtrToStringAuto(ptr, valLength - 1);
- //Parse the buffer into an array of strings by searching for nulls.
- retval = buff.Split('\0');
- }
- return retval;
- }
- #endregion
- #region Write Methods
- /// <summary>
- /// Writes a <see cref="T:System.String"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The string value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- private void WriteValueInternal(string sectionName, string keyName, string value)
- {
- lock (_locks[m_path])
- {
- if (!NativeMethods.WritePrivateProfileString(sectionName, keyName, value, m_path))
- {
- throw new System.ComponentModel.Win32Exception();
- }
- }
- }
- public void WriteValue(string sectionName)
- {
- WriteValueInternal(sectionName, "a", "a");
- WriteValueInternal(sectionName, "a", null);
- //NativeMethods.WritePrivateProfileSection(sectionName, null, m_path);
- }
- /// <summary>
- /// Writes a <see cref="T:System.String"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The string value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> or
- /// <paramref name="value"/> are a null reference (Nothing in VB)
- /// </exception>
- public void WriteValue(string sectionName, string keyName, string value)
- {
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- if (keyName == null)
- throw new ArgumentNullException(nameof(keyName));
- if (value == null)
- throw new ArgumentNullException(nameof(value));
- WriteValueInternal(sectionName, keyName, value);
- }
- /// <summary>
- /// Writes an <see cref="T:System.Int16"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- public void WriteValue(string sectionName, string keyName, short value)
- {
- WriteValue(sectionName, keyName, (int)value);
- }
- /// <summary>
- /// Writes an <see cref="T:System.Int32"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public void WriteValue(string sectionName, string keyName, int value)
- {
- WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
- }
- /// <summary>
- /// Writes an <see cref="T:System.Single"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public void WriteValue(string sectionName, string keyName, float value)
- {
- WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
- }
- /// <summary>
- /// Writes an <see cref="T:System.Double"/> value to the ini file.
- /// </summary>
- /// <param name="sectionName">The name of the section to write to .</param>
- /// <param name="keyName">The name of the key to write to.</param>
- /// <param name="value">The value to write</param>
- /// <exception cref="T:System.ComponentModel.Win32Exception">
- /// The write failed.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public void WriteValue(string sectionName, string keyName, double value)
- {
- WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
- }
- #endregion
- #region Delete Methods
- /// <summary>
- /// Deletes the specified key from the specified section.
- /// </summary>
- /// <param name="sectionName">
- /// Name of the section to remove the key from.
- /// </param>
- /// <param name="keyName">
- /// Name of the key to remove.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> or <paramref name="keyName"/> are
- /// a null reference (Nothing in VB)
- /// </exception>
- public void DeleteKey(string sectionName, string keyName)
- {
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- if (keyName == null)
- throw new ArgumentNullException(nameof(keyName));
- //ArrayList list = ArrayList.Adapter(GetSectionNames());
- //if (!list.Contains(sectionName))
- //{
- // return;
- //}
- //list = ArrayList.Adapter(GetKeyNames(sectionName));
- //if (!list.Contains(keyName))
- //{
- // return;
- //}
- WriteValueInternal(sectionName, keyName, null);
- }
- /// <summary>
- /// Deletes a section from the ini file.
- /// </summary>
- /// <param name="sectionName">
- /// Name of the section to delete.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="sectionName"/> is a null reference (Nothing in VB)
- /// </exception>
- public void DeleteSection(string sectionName)
- {
- if (sectionName == null)
- throw new ArgumentNullException(nameof(sectionName));
- ArrayList list = ArrayList.Adapter(GetSectionNames());
- if (list.Contains(sectionName))
- {
- WriteValueInternal(sectionName, null, null);
- }
- }
- #endregion
- }
- }
|