80 lines
2.1 KiB
C#
80 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Xml.Linq;
|
|
|
|
namespace YLPublishTool.Actions
|
|
{
|
|
/// <summary>
|
|
/// 配置文件
|
|
/// </summary>
|
|
[Description("配置文件")]
|
|
class ConfigAction : IPublishAction
|
|
{
|
|
public string FilePath { get; set; }
|
|
|
|
public string ReplaceContent { get; set; }
|
|
|
|
public void Execute(IPublishContext context)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ReplaceContent))
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(FilePath))
|
|
{
|
|
throw new Exception("文件路径未设置");
|
|
}
|
|
|
|
if (!File.Exists(FilePath))
|
|
{
|
|
throw new Exception("配置文件不存在:" + FilePath);
|
|
}
|
|
|
|
Console.WriteLine("替换配置文件:" + FilePath);
|
|
|
|
var xml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<root>\n{0}\n</root>\n", ReplaceContent);
|
|
var xdoc = XDocument.Parse(xml);
|
|
|
|
xml = File.ReadAllText(FilePath);
|
|
var xdoc2 = XDocument.Parse(xml);
|
|
|
|
var dic = new Dictionary<string, XElement>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
foreach (var xe in xdoc.Root.Elements())
|
|
{
|
|
dic[xe.Name.LocalName] = xe;
|
|
}
|
|
var arr = xdoc2.Root.Elements().ToArray();
|
|
foreach (var xe in arr)
|
|
{
|
|
if (dic.TryGetValue(xe.Name.LocalName, out var xe1))
|
|
{
|
|
xe.ReplaceWith(xe1);
|
|
}
|
|
}
|
|
|
|
xdoc2.Root.Nodes().OfType<XComment>().Remove();
|
|
|
|
xdoc2.Save(FilePath);
|
|
}
|
|
|
|
public void SetProperty(string name, string value)
|
|
{
|
|
switch (name?.ToLowerInvariant())
|
|
{
|
|
case "文件路径":
|
|
case "filepath":
|
|
FilePath = value;
|
|
break;
|
|
case "替换内容":
|
|
ReplaceContent = value;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|