| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- namespace TeamAAS_VP.Core
- {
- /// <summary>
- /// INI配置文件操作类(使用 Windows API)
- /// </summary>
- public class IniConfigHelper
- {
- private readonly string _filePath;
- [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);
- public IniConfigHelper(string iniFileName = "config.ini")
- {
- // 判断路径1
- if (IsPathContainingDirectory(iniFileName))
- {
- if (!Directory.Exists(System.IO.Path.GetDirectoryName(iniFileName)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(iniFileName));
- }
- _filePath=iniFileName;
- }
- else
- {
- // 配置文件存储路径(应用程序所在目录)
- _filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, iniFileName);
- }
-
- // 如果文件不存在则创建
- if (!File.Exists(_filePath))
- {
- File.Create(_filePath).Close();
- }
- }
- public void WriteValue(string section, string key, string value)
- {
- WritePrivateProfileString(section, key, value, _filePath);
- }
- public string ReadValue(string section, string key, string defaultValue = "")
- {
- var sb = new StringBuilder(255);
- GetPrivateProfileString(section, key, defaultValue, sb, 255, _filePath);
- return sb.ToString();
- }
- /// <summary>
- /// 判断路径是否包含文件夹路径
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public bool IsPathContainingDirectory(string path)
- {
- // 获取文件夹路径部分
- string directory = Path.GetDirectoryName(path);
- // 如果目录部分不为空,则表示路径包含文件夹路径
- return !string.IsNullOrEmpty(directory);
- }
- }
- }
|