57 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace SWS.Commons
{
public static class IniHelper
{
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
///读取ini文件数据
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="def">默认值</param>
/// <param name="filePath">文件路径</param>
/// <returns>读出内容</returns>
public static string ReadValueFromIniFile(string Section, string Key, string def=null, string filePath= null)
{
if (def == null)
{ def = ""; }
if (filePath == null)
{
filePath = GlobalObject.configPath;
}
StringBuilder temp = new StringBuilder(4096);
int i = GetPrivateProfileString(Section, Key, def, temp, 4096, filePath);
return temp.ToString();
}
/// <summary>
/// 写入数据到ini文件
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="Value">键值</param>
/// <param name="filePath">文件路径</param>
public static void WriteValueFromIniFile(string Section, string Key, string Value, string filePath = null)
{
if (filePath == null)
{
filePath = GlobalObject.configPath;
}
WritePrivateProfileString(Section, Key, Value, filePath);
}
}
}