From ff40c3b39df3a8da00bbd574c926749145c1f8fe Mon Sep 17 00:00:00 2001 From: Sunny Date: Tue, 27 Feb 2024 22:45:01 +0800 Subject: [PATCH] =?UTF-8?q?*=20UIniConfig:=20=E5=A2=9E=E5=8A=A0=E6=8C=89?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E5=90=8D=E7=A7=B0=E8=BF=9B=E8=A1=8C=E8=AF=BB?= =?UTF-8?q?=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SunnyUI/Common/UIniConfig.cs | 49 +++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/SunnyUI/Common/UIniConfig.cs b/SunnyUI/Common/UIniConfig.cs index 1cf25973..98e3e9d5 100644 --- a/SunnyUI/Common/UIniConfig.cs +++ b/SunnyUI/Common/UIniConfig.cs @@ -18,6 +18,7 @@ * * 2020-01-01: V2.2.0 增加文件说明 * 2022-11-01: V3.2.6 增加文件编码,通过Load传入 + * 2024-02-27: V3.6.3 增加按属性名称进行读写 ******************************************************************************/ using System; @@ -25,7 +26,9 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; +using System.Reflection; using System.Text; +using System.Windows.Forms; namespace Sunny.UI { @@ -43,6 +46,39 @@ namespace Sunny.UI [ConfigIgnore] public Encoding IniEncoding { get; private set; } = Encoding.Default; + [ConfigIgnore] + public object this[string property] + { + get + { + PropertyInfo info = Current.GetType().GetProperty(property); + if (info == null) + { + throw new ArgumentNullException("属性名称不存在:" + property); + } + + return info.GetValue(this, null); + } + set + { + PropertyInfo info = Current.GetType().GetProperty(property); + if (info == null) + { + throw new ArgumentNullException("属性名称不存在:" + property); + } + + try + { + Type propertyType = info.PropertyType; + info.SetValue(Current, Convert.ChangeType(value, propertyType), null); + } + catch (Exception) + { + throw new ArgumentException("属性值转换失败:" + property + ", " + value); + } + } + } + public bool Load(string fileName, Encoding encoding) { IniEncoding = encoding; @@ -188,10 +224,17 @@ namespace Sunny.UI StreamWriter sw = new StreamWriter(filetmp, false, IniEncoding); sw.WriteLine(strs.ToString()); sw.Flush(); - sw.Close(); sw.Dispose(); - File.Delete(filename); - File.Move(filetmp, filename); + + try + { + File.Delete(filename); + File.Move(filetmp, filename); + } + catch (Exception ex) + { + MessageBox.Show("配置文件存储失败: " + filename + " ," + ex.Message); + } } #endregion 加载