using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace YLPublishTool.Actions
{
///
/// 配置文件
///
[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("\n\n{0}\n\n", ReplaceContent);
var xdoc = XDocument.Parse(xml);
xml = File.ReadAllText(FilePath);
var xdoc2 = XDocument.Parse(xml);
var dic = new Dictionary(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().Remove();
xdoc2.Save(FilePath);
}
public void SetProperty(string name, string value)
{
switch (name?.ToLowerInvariant())
{
case "文件路径":
case "filepath":
FilePath = value;
break;
case "替换内容":
ReplaceContent = value;
break;
}
}
}
}