You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
3.0 KiB
83 lines
3.0 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Windows.Input;
|
|
|
|
namespace SunlightAggregationManager.UserClass
|
|
{
|
|
internal class IniFile
|
|
{
|
|
public class IniFiles
|
|
{
|
|
public string path;
|
|
[DllImport("kernel32")] //返回0表示失败,非0为成功
|
|
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);
|
|
/// <summary>
|
|
/// 保存ini文件的路径
|
|
/// 调用示例:var ini = IniFiles("C:\file.ini");
|
|
/// </summary>
|
|
/// <param name="INIPath"></param>
|
|
public IniFiles(string iniPath)
|
|
{
|
|
this.path = iniPath;
|
|
}
|
|
/// <summary>
|
|
/// 写Ini文件
|
|
/// 调用示例:ini.IniWritevalue("Server","name","localhost");
|
|
/// </summary>
|
|
/// <param name="Section">[缓冲区]</param>
|
|
/// <param name="Key">键</param>
|
|
/// <param name="value">值</param>
|
|
public void IniWritevalue(string Section, string Key, string? value)
|
|
{
|
|
// 确保路径有效
|
|
if (!File.Exists(path))
|
|
{
|
|
// 如果文件不存在,创建一个空的
|
|
using (FileStream fs = File.Create(path)) { }
|
|
}
|
|
|
|
// 处理 null 值,避免 API 调用出现问题
|
|
string safeValue = value ?? string.Empty;
|
|
|
|
long result = WritePrivateProfileString(Section, Key, safeValue, path);
|
|
|
|
if (result==0)
|
|
{
|
|
// 可以选择抛出异常或记录日志
|
|
// throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 读Ini文件
|
|
/// 调用示例:ini.IniWritevalue("Server","name");
|
|
/// </summary>
|
|
/// <param name="Section">[缓冲区]</param>
|
|
/// <param name="Key">键</param>
|
|
/// <returns>值</returns>
|
|
public string IniReadvalue(string Section, string Key)
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(path))
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
var sb = new StringBuilder(4096);
|
|
GetPrivateProfileString(Section, Key, string.Empty, sb, sb.Capacity, path);
|
|
return sb.ToString();
|
|
}
|
|
catch (Exception)
|
|
{//错误返回0
|
|
return "0";
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|