标签:
Winform及WPF项目中经常会用到类似SystemSetting.xml等类似的文件用于保存CLIENT的数据,比如登录过的用户名或密码以及其他设置。所以就想到一个解决方法,可以用到所有有此需求的项目中去,避免重复写代码。
1.创建一个Attribute类,用于指定属性在XML文件中的Path
1 namespace ConsoleApplication2 2 { 3 public class NodePathAttribute : Attribute 4 { 5 public string NodePath 6 { 7 get; 8 set; 9 } 10 11 public NodePathAttribute(string nodePath) 12 { 13 NodePath = nodePath; 14 } 15 } 16 }
2.SystemSetting类用于定义要读取和保存的属性,SystemSetting继续XMLSettingBase
1 namespace ConsoleApplication2 2 { 3 public class SystemSetting : XMLSettingBase 4 { 5 #region Property 6 7 #region HostLocationSetting 8 9 /// <summary> 10 /// host wcf service location 11 /// </summary> 12 [NodePath("/Settings/HostLocationSetting/HostLocation")] 13 public string HostLocation { get; set; } 14 15 /// <summary> 16 /// host wcf service port 17 /// </summary> 18 [NodePath("/Settings/HostLocationSetting/HostPort")] 19 public int? HostPort { get; set; } 20 21 #endregion 22 23 #region SystemFolderSetting 24 25 /// <summary> 26 /// NiceLable sdk niceengine5wr.dll path 27 /// </summary> 28 [NodePath("/Settings/SystemFolderSetting/NiceEngineFolderPath")] 29 public string NiceEngineFolderPath 30 { 31 get; 32 set; 33 } 34 35 #endregion 36 37 #region SearchSetting 38 39 /// <summary> 40 /// Main program 41 /// </summary> 42 [NodePath("/Settings/SearchSetting/MainProgram")] 43 public string MainProgram 44 { 45 get; 46 set; 47 } 48 49 /// <summary> 50 /// Sub program 51 /// </summary> 52 [NodePath("/Settings/SearchSetting/SubProgram")] 53 public string SubProgram 54 { 55 get; 56 set; 57 } 58 59 /// <summary> 60 /// Get/Set Date Range to auto setting and search condition 61 /// </summary> 62 [NodePath("/Settings/SearchSetting/DateRange")] 63 public int? DateRange 64 { 65 get; 66 set; 67 } 68 69 /// <summary> 70 /// Get/Set Date Range unit 0:days;1:weeks;2:months;3:years 71 /// </summary> 72 [NodePath("/Settings/SearchSetting/DateRangeUnit")] 73 public int? DateRangeUnit 74 { 75 get; 76 set; 77 } 78 79 /// <summary> 80 /// search status 81 /// </summary> 82 [NodePath("/Settings/SearchSetting/Status")] 83 public FileStatus? Status 84 { 85 get; 86 set; 87 } 88 89 /// <summary> 90 /// Skip printed order 91 /// </summary> 92 [NodePath("/Settings/SearchSetting/SkipPrintedOrder")] 93 public bool? SkipPrintedOrder 94 { 95 get; 96 set; 97 } 98 99 #endregion 100 101 #region PrintSetting 102 103 [NodePath("/Settings/PrintSetting/ReturnQCResult")] 104 public bool? ReturnQCResult { get; set; } 105 106 [NodePath("/Settings/PrintSetting/ActualPrintQuantity")] 107 public bool? ActualPrintQuantity { get; set; } 108 109 [NodePath("/Settings/PrintSetting/MOSeperator")] 110 public bool? MOSeperator { get; set; } 111 112 [NodePath("/Settings/PrintSetting/SKUSeperator")] 113 public string SKUSeperator { get; set; } 114 115 #endregion 116 117 #region LoginSetting 118 119 [NodePath("/Settings/LoginSetting/UserName")] 120 public string UserName { get; set; } 121 122 [NodePath("/Settings/LoginSetting/Password")] 123 public string Password { get; set; } 124 125 [NodePath("/Settings/LoginSetting/Language")] 126 public string Language { get; set; } 127 128 #endregion 129 130 #endregion 131 132 #region Ctor 133 134 public SystemSetting(string filePath) 135 :base(filePath) 136 { 137 138 } 139 140 #endregion 141 } 142 }
1 namespace ConsoleApplication2 2 { 3 public class XMLSettingBase 4 { 5 #region Field 6 7 protected string _filePath = null; 8 protected XmlDocument _xmlDocument = null; 9 10 public delegate void SettingChange(); 11 12 #endregion 13 14 #region Ctor 15 16 public XMLSettingBase(string filePath) 17 { 18 _filePath = filePath; 19 _xmlDocument = new XmlDocument(); 20 _xmlDocument.Load(filePath); 21 } 22 23 #endregion 24 25 #region Event 26 27 public event SettingChange OnSettingChangeEvent; 28 29 #endregion 30 31 #region Method 32 33 /// <summary> 34 /// init system setting 35 /// </summary> 36 public void LoadData() 37 { 38 PropertyInfo[] propertyInfoes = this.GetType().GetProperties(); 39 if (propertyInfoes == null && propertyInfoes.Length == 0) { return; } 40 41 //load each setting value 42 foreach (var propertyInfo in propertyInfoes) 43 { 44 NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); 45 string propertyValue = GetXmlNodeValue(customerAttribute.NodePath); 46 47 PropertyInfoExtension.SetPropertyInfoValue(propertyInfo, this, propertyValue); 48 } 49 } 50 51 /// <summary> 52 /// save data to xml file. 53 /// </summary> 54 private void SaveData() 55 { 56 PropertyInfo[] propertyInfoes = this.GetType().GetProperties(); 57 if (propertyInfoes == null && propertyInfoes.Length == 0) { return; } 58 59 //load each setting value 60 foreach (var propertyInfo in propertyInfoes) 61 { 62 NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); 63 object propertyValue = propertyInfo.GetValue(this); 64 65 SetXmlNodeValue(customerAttribute.NodePath, propertyValue != null ? propertyValue.ToString() : string.Empty); 66 } 67 68 _xmlDocument.Save(_filePath); 69 } 70 71 /// <summary> 72 /// refresh system setting 73 /// </summary> 74 public void Refresh() 75 { 76 //save data 77 SaveData(); 78 //reload the data. 79 LoadData(); 80 //triggering event 81 if (OnSettingChangeEvent != null) 82 { 83 OnSettingChangeEvent(); 84 } 85 } 86 87 public string GetXmlNodeValue(string strNode) 88 { 89 try 90 { 91 XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode); 92 return xmlNode.InnerText; 93 } 94 catch (Exception ex) 95 { 96 throw ex; 97 } 98 } 99 100 public void SetXmlNodeValue(string strNode, string value) 101 { 102 try 103 { 104 XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode); 105 xmlNode.InnerText = value; 106 } 107 catch (Exception ex) 108 { 109 throw ex; 110 } 111 } 112 113 #endregion 114 115 } 116 }
3.PropertyInfoExtension类用于给属性赋值
1 namespace ConsoleApplication2 2 { 3 public static class PropertyInfoExtension 4 { 5 /// <summary> 6 /// convert the datatable to list 7 /// </summary> 8 /// <param name="dt"></param> 9 /// <returns></returns> 10 public static void SetPropertyInfoValue(PropertyInfo propertyInfo, object obj, object value) 11 { 12 //check value 13 if (value == null || string.IsNullOrWhiteSpace(value.ToString())) 14 { 15 return; 16 } 17 18 string strValue = value.ToString(); 19 20 if (propertyInfo.PropertyType.IsEnum) 21 { 22 propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, strValue), null); 23 } 24 else 25 { 26 string propertyTypeName = propertyInfo.PropertyType.Name; 27 switch (propertyTypeName) 28 { 29 case "Int32": 30 case "Int64": 31 case "Int": 32 int intValue; 33 int.TryParse(strValue, out intValue); 34 propertyInfo.SetValue(obj, intValue, null); 35 break; 36 case "Long": 37 long longValue; 38 long.TryParse(strValue, out longValue); 39 propertyInfo.SetValue(obj, longValue, null); 40 break; 41 case "DateTime": 42 DateTime dateTime; 43 DateTime.TryParse(strValue, out dateTime); 44 propertyInfo.SetValue(obj, dateTime, null); 45 break; 46 case "Boolean": 47 Boolean bv = false; 48 if (!"0".Equals(value) || "true".Equals(strValue.ToLower())) 49 { 50 bv = true; 51 } 52 propertyInfo.SetValue(obj, bv, null); 53 break; 54 case "Nullable`1": 55 if (propertyInfo.PropertyType.GenericTypeArguments[0].IsEnum) 56 { 57 propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType.GenericTypeArguments[0], strValue), null); 58 } 59 else 60 { 61 switch (propertyInfo.PropertyType.GenericTypeArguments[0].FullName) 62 { 63 case "System.Int32": 64 case "System.Int64": 65 case "System.Int": 66 int intV; 67 int.TryParse(strValue, out intV); 68 propertyInfo.SetValue(obj, intV, null); 69 break; 70 case "System.DateTime": 71 DateTime dtime; 72 DateTime.TryParse(strValue, out dtime); 73 propertyInfo.SetValue(obj, dtime, null); 74 break; 75 case "System.Boolean": 76 Boolean boolv = false; 77 if (!"0".Equals(value) || "true".Equals(strValue.ToLower())) 78 { 79 boolv = true; 80 } 81 propertyInfo.SetValue(obj, boolv, null); 82 break; 83 default: 84 propertyInfo.SetValue(obj, strValue, null); 85 break; 86 } 87 } 88 break; 89 default: 90 propertyInfo.SetValue(obj, strValue, null); 91 break; 92 } 93 94 } 95 } 96 } 97 }
4.测试用类
1 这是需要操作的文件 2 <?xml version="1.0" encoding="utf-8" ?> 3 <Settings> 4 <HostLocationSetting> 5 <HostLocation></HostLocation> 6 <HostPort></HostPort> 7 </HostLocationSetting> 8 <SystemFolderSetting> 9 <NiceEngineFolderPath></NiceEngineFolderPath> 10 </SystemFolderSetting> 11 <SearchSetting> 12 <MainProgram></MainProgram> 13 <SubProgram></SubProgram> 14 <Status></Status> 15 <SkipPrintedOrder>true</SkipPrintedOrder> 16 <DateRange>1</DateRange> 17 <DateRangeUnit>0</DateRangeUnit> 18 </SearchSetting> 19 <PrintSetting> 20 <ReturnQCResult>false</ReturnQCResult> 21 <ActualPrintQuantity></ActualPrintQuantity> 22 <MOSeperator>true</MOSeperator> 23 <SKUSeperator></SKUSeperator> 24 </PrintSetting> 25 <LoginSetting> 26 <UserName></UserName> 27 <Password></Password> 28 <Language></Language> 29 </LoginSetting> 30 31 </Settings> 32 33 34 测试代码如下 35 namespace ConsoleApplication2 36 { 37 class Program 38 { 39 static void Main(string[] args) 40 { 41 SystemSetting systemSetting = new SystemSetting(@"Config/SystemSetting.xml"); 42 43 systemSetting.LoadData(); 44 45 Console.WriteLine(systemSetting.HostLocation); 46 Console.WriteLine(systemSetting.Status); 47 Console.WriteLine(systemSetting.SkipPrintedOrder); 48 49 systemSetting.HostLocation = "192.168.15.171"; 50 systemSetting.Status = FileStatus.PARTIAL_PRINTED; 51 systemSetting.SkipPrintedOrder = true; 52 53 systemSetting.Refresh(); 54 55 systemSetting.LoadData(); 56 57 Console.WriteLine(systemSetting.HostLocation); 58 Console.WriteLine(systemSetting.Status); 59 Console.WriteLine(systemSetting.SkipPrintedOrder); 60 61 Console.ReadKey(); 62 63 } 64 } 65 }
项目常用解决方案之SystemSetting.xml文件的修改与读取
标签:
原文地址:http://www.cnblogs.com/JustYong/p/4233378.html