Files
6098/Cowain.Bake.Common/Core/INIHelper.cs

104 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Cowain.Bake.Common.Core
{
public class INIHelper
{
[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);
//ini文件名称
private static string inifilename = "Config.ini";
//获取ini文件路径
public static string inifilepath = Application.StartupPath + "\\" + inifilename;
public static string ReadValue(string key)
{
StringBuilder s = new StringBuilder(1024);
GetPrivateProfileString("Config", key, "", s, 1024, inifilepath);
return s.ToString();
}
public static bool ReadBool(string section, string key, bool value = false)
{
bool reVal = false;
StringBuilder s = new StringBuilder(1024);
GetPrivateProfileString(section, key, "", s, 1024, inifilepath);
bool b = bool.TryParse(s.ToString(), out reVal);
if (b)
{
return reVal;
}
return value;
}
public static string ReadString(string section, string key, string value = "")
{
StringBuilder s = new StringBuilder(1024);
GetPrivateProfileString(section, key, "", s, 1024, inifilepath);
if (0 == s.ToString().Length)
{
return value;
}
return s.ToString();
}
public static int ReadInt(string section, string key, int nDefault = 0)
{
// 每次从ini中读取多少字节
System.Text.StringBuilder temp = new StringBuilder(1024);
// section=配置节key=键名temp=上面path=路径
GetPrivateProfileString(section, key, "", temp, 1024, inifilepath);
string t = temp.ToString();
int v = 0;
if (int.TryParse(t, out v))
{
return v;
}
return nDefault;
}
public static float ReadFloat(string section, string key, float fDefault = 0)
{
// 每次从ini中读取多少字节
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
// section=配置节key=键名temp=上面path=路径
GetPrivateProfileString(section, key, "", temp, 255, inifilepath);
string t = temp.ToString();
float v = 0;
if (float.TryParse(t, out v))
{
return v;
}
return fDefault;
}
/// <param name="value"></param>
public static void Write(string section, string key, string value)
{
// section=配置节key=键名value=键值path=路径
WritePrivateProfileString(section, key, value, inifilepath);
}
public static void WriteValue(string key, string value)
{
try
{
WritePrivateProfileString("Config", key, value, inifilepath);
}
catch (Exception ex)
{
throw ex;
}
}
}
}