使用构建操作“无”将所有文件设置为“始终复制到输出目录”的最简单方法

时间:2014-06-18 12:08:47

标签: visual-studio

我必须在Visual Studio项目中添加许多文件(1000+)。新添加的最初不属于项目类型的文件将添加构建操作'无'和输出模式设置为“不要复制'

我想将输出操作更改为'始终复制'。如果你们没有提出更聪明的想法,我会建立一个控制台应用程序,并从

进行相同的Xml转换
<None Include="some\file.json" />

<None Include="some\file.json">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

1 个答案:

答案 0 :(得分:0)

我在Shaun Xu的博客文章中找到了该解决方案。通过命令行arg提供proj文件,所有Content / None项目都设置为Copy always。

static void Main(string[] args)
{
    if (args.Length < 1)
    {
        Console.WriteLine("Usage: copyallalways [project file]");
        return;
    }

    var proj = args[0];
    File.Copy(proj, string.Format("{0}.bak", proj));

    var xml = new XmlDocument();
    xml.Load(proj);
    var nsManager = new XmlNamespaceManager(xml.NameTable);
    nsManager.AddNamespace("pf", "http://schemas.microsoft.com/developer/msbuild/2003");

    // add the output setting to copy always
    var contentNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:Content", nsManager);
    UpdateNodes(contentNodes, xml, nsManager);
    var noneNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:None", nsManager);
    UpdateNodes(noneNodes, xml, nsManager);
    xml.Save(proj);

    // remove the namespace attributes
    var content = xml.InnerXml.Replace("<CopyToOutputDirectory xmlns=\"\">", "<CopyToOutputDirectory>");
    xml.LoadXml(content);
    xml.Save(proj);
}

static void UpdateNodes(XmlNodeList nodes, XmlDocument xml, XmlNamespaceManager nsManager)
{
    foreach (XmlNode node in nodes)
    {
        var copyToOutputDirectoryNode = node.SelectSingleNode("pf:CopyToOutputDirectory", nsManager);
        if (copyToOutputDirectoryNode == null)
        {
            var n = xml.CreateNode(XmlNodeType.Element, "CopyToOutputDirectory", null);
            n.InnerText = "Always";
            node.AppendChild(n);
        }
        else
        {
            if (string.Compare(copyToOutputDirectoryNode.InnerText, "Always", true) != 0)
            {
                copyToOutputDirectoryNode.InnerText = "Always";
            }
        }
    }
}