维护更新
This commit is contained in:
@@ -1,49 +0,0 @@
|
||||
using System.Configuration;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists
|
||||
{
|
||||
public class ConfigAssist
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取项目文件夹下的配置文件根据Key获取Value
|
||||
/// </summary>
|
||||
/// <param name="key">键</param>
|
||||
/// <returns></returns>
|
||||
public static string GetCfgValue(string key)
|
||||
{
|
||||
var assembly = Assembly.GetCallingAssembly();
|
||||
|
||||
var uri = new Uri(Path.GetDirectoryName(assembly.Location) ?? string.Empty);
|
||||
var map = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config") };
|
||||
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
|
||||
var loadpath = config.AppSettings.Settings[key].Value; //若路径存在则自动获取该路径
|
||||
return loadpath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存到程序目录下的配置文件
|
||||
/// </summary>
|
||||
/// <param name="key">键</param>
|
||||
/// <param name="value">值</param>
|
||||
public static void SetCfgPairs(string key, string value)
|
||||
{
|
||||
var assembly = Assembly.GetCallingAssembly();
|
||||
var uri = new Uri(Path.GetDirectoryName(assembly.Location) ?? string.Empty);
|
||||
var map = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config") };
|
||||
|
||||
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
|
||||
config.AppSettings.Settings[key].Value = value; //将用户选取的路径_path赋给app.config中的_path(名称自取)
|
||||
//ConfigurationManager.OpenMappedExeConfiguration(map, 0).AppSettings.Settings["FamilyPath"].Value = SelectedPath;
|
||||
config.AppSettings.SectionInformation.ForceSave = true;
|
||||
|
||||
config.Save(ConfigurationSaveMode.Modified); //将配置保存
|
||||
ConfigurationManager.RefreshSection("appSettings"); //刷新配置文件
|
||||
//if (Directory.Exists(config.AppSettings.Settings["FamilyPath"].Value))//判断配置的路径是否存在
|
||||
//{
|
||||
// dialog.SelectedPath = config.AppSettings.Settings["FamilyPath"].Value;//若路径存在则自动获取该路径
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists;
|
||||
|
||||
public static class IOAssist
|
||||
{
|
||||
public static void GetFilesHierarchy(string path)
|
||||
{
|
||||
var files = Directory.GetFiles($"{path}", "*", SearchOption.AllDirectories); //遍历所有文件夹
|
||||
var list = files.Union(files).OrderBy(s => s);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取当前文件的副本或备份文件名
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="FileNotFoundException"></exception>
|
||||
public static string GetUniqueFilePath(string filePath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
|
||||
{
|
||||
throw new FileNotFoundException($"文件'{filePath}'不存在。");
|
||||
}
|
||||
var dir = Path.GetDirectoryName(filePath);
|
||||
var extension = Path.GetExtension(filePath);
|
||||
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
|
||||
var counter = 1;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var candidateFileName = $"{fileNameWithoutExtension}.{counter:D3}{extension}";
|
||||
var fullPath = Path.Combine(dir, candidateFileName);
|
||||
if (!File.Exists(fullPath))
|
||||
{
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
public static string GetRelativePath(string fromPath, string toPath)
|
||||
{
|
||||
Uri uri = new(fromPath);
|
||||
Uri uri2 = new(toPath);
|
||||
if (uri.Scheme != uri2.Scheme)
|
||||
{
|
||||
return toPath;
|
||||
}
|
||||
|
||||
var uri3 = uri.MakeRelativeUri(uri2);
|
||||
var text = Uri.UnescapeDataString(uri3.ToString());
|
||||
if (uri2.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
text = text.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定系统路径
|
||||
/// </summary>
|
||||
/// <param name="specialFolder"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetSpecialFolderDir(Environment.SpecialFolder specialFolder)
|
||||
{
|
||||
return Environment.GetFolderPath(specialFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读文件
|
||||
/// </summary>
|
||||
/// <param name="path">文件路径</param>
|
||||
/// <returns></returns>
|
||||
public static string ReadFile(string path)
|
||||
{
|
||||
string s;
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
s = "不存在相应的目录";
|
||||
}
|
||||
else
|
||||
{
|
||||
using StreamReader f2 = new(path, Encoding.GetEncoding("gb2312"));
|
||||
s = f2.ReadToEnd();
|
||||
f2.Close();
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在桌面写文件
|
||||
/// </summary>
|
||||
/// <param name="fileName">纯文件名</param>
|
||||
/// <param name="message">写入的内容</param>
|
||||
public static void WriteTxtFile(string fileName, string message)
|
||||
{
|
||||
var filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\{fileName}.txt";
|
||||
File.WriteAllText(filePath, message);
|
||||
Process.Start(filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写文件
|
||||
/// </summary>
|
||||
/// <param name="path">文件路径</param>
|
||||
/// <param name="strings">文件内容</param>
|
||||
public static void WriteFile(string path, string strings)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
var f = File.Create(path);
|
||||
f.Close();
|
||||
f.Dispose();
|
||||
}
|
||||
|
||||
using StreamWriter f2 = new(path, true, Encoding.UTF8);
|
||||
f2.WriteLine(strings);
|
||||
f2.Close();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向文本文件中写入内容
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
/// <param name="text">写入的内容</param>
|
||||
/// <param name="encoding">编码</param>
|
||||
public static void WriteText(string filePath, string text, Encoding encoding)
|
||||
{
|
||||
//向文件写入内容
|
||||
File.WriteAllText(filePath, text, encoding);
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists;
|
||||
|
||||
public class IniAssist
|
||||
{
|
||||
public IniAssist(string iniPath)
|
||||
{
|
||||
path = iniPath;
|
||||
}
|
||||
|
||||
public string path;
|
||||
|
||||
/// <summary>
|
||||
/// 删除ini文件下所有段落
|
||||
/// </summary>
|
||||
public void ClearAllSection()
|
||||
{
|
||||
IniWriteValue(null, null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除ini文件下personal段落下的所有键
|
||||
/// </summary>
|
||||
/// <param name="section"></param>
|
||||
public void ClearSection(string section)
|
||||
{
|
||||
IniWriteValue(section, null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取INI文件
|
||||
/// </summary>
|
||||
/// <param name="section"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public string IniReadValue(string section, string key)
|
||||
{
|
||||
var temp = new StringBuilder(255);
|
||||
GetPrivateProfileString(section, key, "", temp, 255, path);
|
||||
return temp.ToString();
|
||||
}
|
||||
|
||||
public byte[] IniReadValues(string section, string key)
|
||||
{
|
||||
var temp = new byte[255];
|
||||
var i = GetPrivateProfileString(section, key, "", temp, 255, path);
|
||||
return temp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写INI文件
|
||||
/// </summary>
|
||||
/// <param name="section"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
public void IniWriteValue(string section, string key, string value)
|
||||
{
|
||||
WritePrivateProfileString(section, key, value, path);
|
||||
}
|
||||
|
||||
[DllImport("kernel32")]
|
||||
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
|
||||
|
||||
[DllImport("kernel32")]
|
||||
private static extern int GetPrivateProfileString(string section, string key, string defVal, byte[] retVal, int size, string filePath);
|
||||
|
||||
[DllImport("kernel32")]
|
||||
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Management;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists
|
||||
{
|
||||
public class LicenseEngine
|
||||
{
|
||||
// 【重要】替换为你生成的公钥
|
||||
private const string PublicKey = @"<RSAKeyValue><Modulus>rd5+EjU6QxaTY/AalU9g6ugAquN0ahJSgeahnf2CrfvUAWFNJ+SH7Qr0RcvOTyAbWfvLWoBDACKaPsg+8nRQcO3EZdFyjJ9oycLNrw38+gSB2+/79Axys/8MHtSXVUw9WN2e9LxeHOQGtcaoSsp+bPGaXswthovQ2CkvBTmCokcAOX6UaR7Av4npaXyEoGCUsZLEiSydMsNbQ+wLsumVg1H2o/cpkO0s4DiJHoF66zUuxA+pYSjSCn5KTUsOemf+gBsob6Sw+7WOToyiOkMdO9Op6esf8yL7DJ1Yd40XaKd5IeLQmEX/b+n1EV2JEkGO0p9q9MQRp6NrEc9LvfMJWQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
|
||||
|
||||
private static string RegPath = @$"Software\{Assembly.GetExecutingAssembly().GetName()}\License";
|
||||
|
||||
/// <summary>
|
||||
/// 完整验证逻辑
|
||||
/// </summary>
|
||||
public static (bool isValid, string message) Validate()
|
||||
{
|
||||
string licenseKey = LoadFromRegistry("Key");
|
||||
if (string.IsNullOrEmpty(licenseKey)) return (false, "未找到授权码");
|
||||
|
||||
try
|
||||
{
|
||||
// 1. RSA 解密/验证逻辑
|
||||
// 激活码格式:签名(Base64)|机器码|到期日期
|
||||
var parts = licenseKey.Split('|');
|
||||
if (parts.Length != 3) return (false, "授权格式非法");
|
||||
|
||||
string signature = parts[0];
|
||||
string mCode = parts[1];
|
||||
string expiryStr = parts[2];
|
||||
|
||||
// 2. 验证是否是本机的机器码
|
||||
if (mCode != GetMachineCode()) return (false, "授权码与本机硬件不匹配");
|
||||
|
||||
// 3. 验证 RSA 签名(确保数据没被篡改)
|
||||
if (!VerifySignature($"{mCode}|{expiryStr}", signature)) return (false, "授权签名校验失败");
|
||||
|
||||
// 4. 时间校验
|
||||
DateTime expiryDate = DateTime.ParseExact(expiryStr, "yyyyMMdd", CultureInfo.InvariantCulture);
|
||||
DateTime now = GetRobustDateTime();
|
||||
|
||||
// 防回滚检查
|
||||
DateTime lastRun = GetLastRunTime();
|
||||
if (now < lastRun) return (false, "系统时间异常,请检查时钟");
|
||||
UpdateLastRunTime(now);
|
||||
|
||||
if (now > expiryDate) return (false, $"授权已于 {expiryDate:yyyy-MM-dd} 到期");
|
||||
|
||||
return (true, "授权有效");
|
||||
}
|
||||
catch { return (false, "解析授权出错"); }
|
||||
}
|
||||
|
||||
private static bool VerifySignature(string data, string signature)
|
||||
{
|
||||
using (var rsa = new RSACryptoServiceProvider())
|
||||
{
|
||||
rsa.FromXmlString(PublicKey);
|
||||
var formatter = new RSAPKCS1SignatureDeformatter(rsa);
|
||||
formatter.SetHashAlgorithm("SHA256");
|
||||
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
|
||||
using (var sha = SHA256.Create())
|
||||
{
|
||||
byte[] hash = sha.ComputeHash(dataBytes);
|
||||
return formatter.VerifySignature(hash, Convert.FromBase64String(signature));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetMachineCode()
|
||||
{
|
||||
// 组合 CPU ID + 硬盘 ID
|
||||
string raw = GetHardwareId("Win32_Processor", "ProcessorId") +
|
||||
GetHardwareId("Win32_PhysicalMedia", "SerialNumber");
|
||||
using (var sha = SHA256.Create())
|
||||
{
|
||||
byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(raw));
|
||||
return BitConverter.ToString(hash).Replace("-", "").Substring(0, 16);
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetHardwareId(string wmiClass, string property)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var mc = new ManagementClass(wmiClass))
|
||||
foreach (var mo in mc.GetInstances()) return mo[property]?.ToString().Trim();
|
||||
}
|
||||
catch { }
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
// 获取可靠的时间(网络优先,本地其次)
|
||||
private static DateTime GetRobustDateTime()
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = WebRequest.Create("http://www.baidu.com");
|
||||
request.Timeout = 2000;
|
||||
using (var response = request.GetResponse())
|
||||
{
|
||||
string dateStr = response.Headers["Date"];
|
||||
return DateTime.ParseExact(dateStr, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
|
||||
}
|
||||
}
|
||||
catch { return DateTime.Now; }
|
||||
}
|
||||
|
||||
#region 注册表操作
|
||||
private static DateTime GetLastRunTime()
|
||||
{
|
||||
string val = LoadFromRegistry("T");
|
||||
return string.IsNullOrEmpty(val) ? DateTime.MinValue : new DateTime(long.Parse(val));
|
||||
}
|
||||
private static void UpdateLastRunTime(DateTime now) => SaveToRegistry("T", now.Ticks.ToString());
|
||||
|
||||
public static void SaveToRegistry(string key, string val)
|
||||
{
|
||||
using var r = Registry.CurrentUser.CreateSubKey(RegPath);
|
||||
r.SetValue(key, val);
|
||||
}
|
||||
private static string LoadFromRegistry(string key)
|
||||
{
|
||||
using var r = Registry.CurrentUser.OpenSubKey(RegPath);
|
||||
return r?.GetValue(key)?.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 仅移除当前的激活码(重置授权状态,但保留时间戳防止白嫖)
|
||||
/// </summary>
|
||||
public static void ClearLicenseKey()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var r = Registry.CurrentUser.OpenSubKey(RegPath, true))
|
||||
{
|
||||
if (r != null && r.GetValue("Key") != null)
|
||||
{
|
||||
r.DeleteValue("Key");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("移除授权码失败: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 彻底销毁所有授权痕迹(包括时间戳记录,通常用于卸载)
|
||||
/// </summary>
|
||||
public static void DestroyAllLicenseData()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 第二个参数为 false 表示:如果路径不存在,不抛出异常
|
||||
Registry.CurrentUser.DeleteSubKeyTree(RegPath, false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("彻底清理注册表失败: " + ex.Message);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists;
|
||||
|
||||
public static class SingletonChildWindowManager
|
||||
{
|
||||
private static readonly Dictionary<Type, Window> Windows = [];
|
||||
public static void ShowOrActivate<TWindow, TViewModel>(params object[] viewModelParams)
|
||||
where TWindow : Window, new()
|
||||
where TViewModel : class
|
||||
{
|
||||
var windowType = typeof(TWindow);
|
||||
if (Windows.TryGetValue(windowType, out var window) && window != null)
|
||||
{
|
||||
window.Activate();
|
||||
}
|
||||
else
|
||||
{
|
||||
//CloseAllWindowsExcept(windowType);
|
||||
Windows[windowType] = new TWindow();
|
||||
Windows[windowType].Closed += (_, _) => Windows[windowType] = null;
|
||||
if (Windows[windowType].DataContext == null || Windows[windowType].DataContext is not TViewModel)
|
||||
{
|
||||
Windows[windowType].DataContext = viewModelParams.Length == 0
|
||||
? Activator.CreateInstance<TViewModel>()
|
||||
: Activator.CreateInstance(typeof(TViewModel), viewModelParams);
|
||||
}
|
||||
_ = new WindowInteropHelper(Windows[windowType]) { Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle };
|
||||
Windows[windowType].Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,426 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace ShrlAlgoToolkit.Core.Assists;
|
||||
|
||||
public class XmlAssist
|
||||
{
|
||||
public XmlAssist(string strPath)
|
||||
{
|
||||
XmlPath = strPath;
|
||||
}
|
||||
|
||||
public string XmlPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建配置文件,可在子类中重写此方法
|
||||
/// </summary>
|
||||
public static void CreateFile(string fileName)
|
||||
{
|
||||
var doc = new XmlDocument();
|
||||
var dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
|
||||
doc.AppendChild(dec);
|
||||
var root = doc.CreateElement("Root");
|
||||
doc.AppendChild(root);
|
||||
root.AppendChild(doc.CreateElement("Config"));
|
||||
doc.Save(fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除节点值
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
public static void Delete(string path, string node)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
xn.ParentNode.RemoveChild(xn);
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除数据
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
|
||||
public static void Delete(string path, string node, string attribute)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
var xe = (XmlElement)xn;
|
||||
if (attribute.Equals(string.Empty))
|
||||
{
|
||||
xn.ParentNode.RemoveChild(xn);
|
||||
}
|
||||
else
|
||||
{
|
||||
xe.RemoveAttribute(attribute);
|
||||
}
|
||||
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 插入数据
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
|
||||
/// <param name="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param>
|
||||
/// <param name="value">值</param>
|
||||
public static void Insert(string path, string node, string element, string attribute, string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = new XmlDocument();
|
||||
doc.Load(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
if (element.Equals(string.Empty))
|
||||
{
|
||||
if (!attribute.Equals(string.Empty))
|
||||
{
|
||||
var xe = (XmlElement)xn;
|
||||
xe.SetAttribute(attribute, value);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var xe = doc.CreateElement(element);
|
||||
if (attribute.Equals(string.Empty))
|
||||
{
|
||||
xe.InnerText = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
xe.SetAttribute(attribute, value);
|
||||
}
|
||||
|
||||
xn.AppendChild(xe);
|
||||
}
|
||||
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 插入数据
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
|
||||
/// <param name="strList">由XML属性名和值组成的二维数组</param>
|
||||
public static void Insert(string path, string node, string element, string[][] strList)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = new XmlDocument();
|
||||
doc.Load(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
var xe = doc.CreateElement(element);
|
||||
var strAttribute = string.Empty;
|
||||
var strValue = string.Empty;
|
||||
for (var i = 0; i < strList.Length; i++)
|
||||
{
|
||||
for (var j = 0; j < strList[i].Length; j++)
|
||||
{
|
||||
if (j == 0)
|
||||
{
|
||||
strAttribute = strList[i][j];
|
||||
}
|
||||
else
|
||||
{
|
||||
strValue = strList[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
if (strAttribute.Equals(string.Empty))
|
||||
{
|
||||
xe.InnerText = strValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
xe.SetAttribute(strAttribute, strValue);
|
||||
}
|
||||
}
|
||||
|
||||
xn.AppendChild(xe);
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
public static void parsexmldoc(string file)
|
||||
{
|
||||
var document = XDocument.Load(file);
|
||||
//获取到XML的根元素进行操作
|
||||
var root = document.Root;
|
||||
if (root.FirstAttribute.Value == "车辆轮廓点")
|
||||
{
|
||||
//获取根元素下的所有子元素
|
||||
var enumerable = root.Elements();
|
||||
foreach (var xe in enumerable)
|
||||
{
|
||||
//IEnumerable<XElement> pts = xe.Elements();
|
||||
|
||||
//KineModel data = new KineModel();
|
||||
//data.StrPosition = xe.Name.LocalName;
|
||||
//data.Name = (string)xe.Attribute("点号");
|
||||
//data.X = (double)xe.Attribute("X");
|
||||
//data.Y = (double)xe.Attribute("Y");
|
||||
//vm.Items.Add(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取指定节点的数据
|
||||
/// </summary>
|
||||
/// <param name="node">节点</param>
|
||||
/// <returns>The <see cref="string" /></returns>
|
||||
public string Read(string node)
|
||||
{
|
||||
var value = string.Empty;
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad();
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
if (xn != null)
|
||||
{
|
||||
value = xn.InnerText;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取指定路径和节点的串联值
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <returns>The <see cref="string" /></returns>
|
||||
public static string Read(string path, string node)
|
||||
{
|
||||
var value = string.Empty;
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
value = xn.InnerText;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取指定路径和节点的属性值
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
|
||||
/// <returns>The <see cref="string" /></returns>
|
||||
public static string Read(string path, string node, string attribute)
|
||||
{
|
||||
var value = string.Empty;
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
value = attribute.Equals(string.Empty) ? xn.InnerText : xn.Attributes[attribute].Value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取某一节点的所有子节点的值
|
||||
/// </summary>
|
||||
/// <param name="node">要查询的节点</param>
|
||||
/// <returns>The <see cref="XmlNodeList" /></returns>
|
||||
public XmlNodeList ReadAllChild(string node)
|
||||
{
|
||||
var doc = XmlLoad();
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
var nodelist = xn.ChildNodes; //得到该节点的子节点
|
||||
return nodelist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取某一节点的所有孩子节点的值
|
||||
/// </summary>
|
||||
/// <param name="node">要查询的节点</param>
|
||||
public string[] ReadAllChildallValue(string node)
|
||||
{
|
||||
var i = 0;
|
||||
string[] str = { };
|
||||
var doc = XmlLoad();
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
if (xn != null)
|
||||
{
|
||||
var nodelist = xn.ChildNodes; //得到该节点的子节点
|
||||
if (nodelist.Count > 0)
|
||||
{
|
||||
str = new string[nodelist.Count];
|
||||
foreach (XmlElement el in nodelist) //读元素值
|
||||
{
|
||||
str[i] = el.Value;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改指定节点的数据
|
||||
/// </summary>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="value">值</param>
|
||||
public void Update(string node, string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad();
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
xn.InnerText = value;
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + XmlPath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改指定节点的数据
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="value">值</param>
|
||||
public static void Update(string path, string node, string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
xn.InnerText = value;
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改指定节点的属性值(静态)
|
||||
/// </summary>
|
||||
/// <param name="path">路径</param>
|
||||
/// <param name="node">节点</param>
|
||||
/// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param>
|
||||
/// <param name="value">值</param>
|
||||
public static void Update(string path, string node, string attribute, string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var doc = XmlLoad(path);
|
||||
var xn = doc.SelectSingleNode(node);
|
||||
var xe = (XmlElement)xn;
|
||||
if (attribute.Equals(string.Empty))
|
||||
{
|
||||
xe.InnerText = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
xe.SetAttribute(attribute, value);
|
||||
}
|
||||
|
||||
doc.Save(AppDomain.CurrentDomain.BaseDirectory + path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
private XmlDocument XmlLoad()
|
||||
{
|
||||
var XMLFile = XmlPath;
|
||||
var xmldoc = new XmlDocument();
|
||||
try
|
||||
{
|
||||
var filename = AppDomain.CurrentDomain.BaseDirectory + XMLFile;
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
xmldoc.Load(filename);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return xmldoc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导入XML文件
|
||||
/// </summary>
|
||||
/// <param name="strPath">The strPath<see cref="string" /></param>
|
||||
/// <returns>The <see cref="XmlDocument" /></returns>
|
||||
private static XmlDocument XmlLoad(string strPath)
|
||||
{
|
||||
var xmldoc = new XmlDocument();
|
||||
try
|
||||
{
|
||||
var filename = AppDomain.CurrentDomain.BaseDirectory + strPath;
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
xmldoc.Load(filename);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return xmldoc;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user