您可以使用手写的 C#、脚本、powershell 或类似工具来搜索和替换正则表达式。但它存在以下问题:
- 难以阅读(在三个月或更长时间内阅读你漂亮的正则表达式)
- 难以增强(新的搜索/替换/检查功能的新正则表达式)
- 容易破解(ms build 项目的新版本/格式或非预测标签可能不起作用)
- 更难测试(您必须检查没有发生意外匹配)
- 难以维护(由于上述原因)
以及以下优点:
- 不做任何额外的验证(可能)让它适用于任何类型的项目(单声道或视觉)。
- 不在乎 \r :)
最好的办法是使用Microsoft.Build.Evaluation
并构建一个 C# 工具来执行所有测试/检查/修复等。
我已经完成了一个命令行工具,它使用源文件列表(由 Mono 使用)并更新 csproj 的源以及另一个在控制台上转储 csproj 内容的源。这很容易做到,非常简单且易于测试。
但是,它可能会在由“非” Ms 工具(如 Mono Studio)修改的项目上或由于缺少\r ...而失败(正如我所经历的那样)。无论如何,您始终可以使用异常捕获和好消息。
这是使用 Microsoft.Build.dll 的示例(不要使用 Microsof.Build.Engine,因为它已过时):
using System;
using Microsoft.Build.Evaluation;
internal class Program
{
private static void Main(string[] args)
{
var project = new Project("PathToYourProject.csproj");
Console.WriteLine(project.GetProperty("TargetFrameworkVersion", true, string.Empty));
Console.WriteLine(project.GetProperty("Platform", true, string.Empty));
Console.WriteLine(project.GetProperty("WarningLevel", true, string.Empty));
Console.WriteLine(project.GetProperty("TreatWarningsAsErrors", true, "false"));
Console.WriteLine(project.GetProperty("OutputPath", false, string.Empty));
Console.WriteLine(project.GetProperty("SignAssembly", true, "false"));
Console.WriteLine(project.GetProperty("AssemblyName", false, string.Empty));
Console.ReadLine();
}
}
public static class ProjectExtensions
{
public static string GetProperty(this Project project, string propertyName, bool afterEvaluation, string defaultValue)
{
var property = project.GetProperty(propertyName);
if (property != null)
{
if (afterEvaluation)
return property.EvaluatedValue;
return property.UnevaluatedValue;
}
return defaultValue;
}
}