Client/Desktop/KMBIM3.0/23.10.16/Utils/SettingHelper.cs

118 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace KMBIM.Revit.Tools.Utils
{
public class SettingHelper
{
private static string a;
private static string b;
protected static Configuration _configuration;
public static string FilePath
{
get
{
return a;
}
set
{
a = value;
}
}
public static string RootElementName
{
get
{
return b;
}
set
{
b = value;
}
}
public static Configuration Configuration = _configuration;
static SettingHelper()
{
RootElementName = "configuration";
_configuration = new Configuration();
}
public static bool Load(string filePath = "")
{
_configuration.Clear();
if (!string.IsNullOrEmpty(filePath))
{
FilePath = filePath;
}
if (string.IsNullOrEmpty(FilePath) || !File.Exists(FilePath))
{
return false;
}
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(FilePath);
XmlNode xmlNode = xmlDocument[RootElementName];
if (xmlNode != null)
{
foreach (XmlNode childNode in xmlNode.ChildNodes)
{
_configuration[childNode.Name] = childNode.InnerText;
}
return true;
}
return false;
}
catch (Exception)
{
_configuration.Clear();
return false;
}
}
public static bool Save()
{
if (string.IsNullOrEmpty(FilePath))
{
return false;
}
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><{0}></{0}>", RootElementName));
XmlNode xmlNode = xmlDocument[RootElementName];
foreach (string key in _configuration.Keys)
{
XmlNode xmlNode2 = xmlDocument.CreateNode(XmlNodeType.Element, key, null);
xmlNode2.InnerText = _configuration[key];
xmlNode.AppendChild(xmlNode2);
}
xmlDocument.Save(FilePath);
return false;
}
catch (Exception)
{
_configuration.Clear();
return false;
}
}
}
}