我想要在所有源代码文件中检测特定的单词或模式.例如,如果我想限制在项目中使用DateTime.Now,但如果某个团队成员在源代码中使用了它,我希望生成操作失败.

我不知道什么是正确的方法,但我可以使用VS预构建事件来实现同样的目的吗?如果没有,那么有没有人可以 bootstrap 我走上正确的道路来满足我的要求?

推荐答案

您可以通过在PreBuildEvent中输入类似PowerShell MyPowerShellScript.ps1的命令来执行PowerShell脚本.这些脚本包括在所有源代码文件中搜索特定的单词或模式.

请按照以下步骤操作.(示例)

  1. PowerShell脚本
$results = Get-ChildItem -Path {your project path} -Recurse | Select-String -Pattern "DateTime.Now";
if([string]::IsNullOrEmpty($results)){
  Write-Host "not found specific word DateTime.Now"
}else{
  Write-Host " found specific word DateTime.Now"
  #other than zero (0)
  exit 1
}

Note:

让您的事件操作以非零(0)代码退出.零退出代码表示操作成功;任何其他退出代码都被视为错误.

2.Enter a command like PowerShell MyPowerShellScript.ps1. On the Project menu->click {ProjectName} Properties (or from Solution Explorer, press Alt+Enter)->Select Build > Events. enter image description here

Visual Studio通过添加PreBuildTarget和必要的MSBuild代码来修改项目文件,以执行您提供的步骤.

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
  <Exec Command="PowerShell {your project path}\pw.ps1" />
</Target>

3.Build the project and watch the output window. If it finds the specific world(DateTime.Now) in your source code files, the script exits with code 1 and the build fails. enter image description here

希望它能对你有所帮助.

Csharp相关问答推荐

Rx.Net -当关闭序列被触发时如何聚合消息并发出中间输出?

在依赖性注入和继承之间进行 Select

ASP.NET核心结果.文件vs结果.流

C#EF Core 8.0表现与预期不符

用C#调用由缓冲区指针参数组成的C API

使用可信第三方的Iext8.Net pdf签名

带有列表参数的表达式树

是否由DI容器自动处理由ActivatorUilties.CreateInstance()创建的服务?

Azure函数-在外部启动类中生成配置时出错

为什么我的伺服电机不动,下面的代码?

如何在Akka.NET中重新启动执行元时清除邮箱

发布.NET 8 Blazor WebAssembly独立应用程序以进行静态站点部署

如何对特定异常使用Polly重试机制?

从GRPC连接创建ZipArchive

为什么我的自定义Json.net转换器不工作?

RavenDb:为什么在字符串==空的情况下过滤会过滤得太多?

并发表更新.EF核心交易

使用DI实例化带有动态参数的服务?

我可以阻止类型上的Object.ToString()吗?

C#If条件格式