C# 将所有警告视为错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17533008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:46:14  来源:igfitidea点击:

Treat all warnings as errors

c#.nettfsmsbuildwarnings

提问by ken2k

This should be obvious to do, but I just couldn't make it work...

这应该是显而易见的,但我无法让它发挥作用......

What I'm trying to do is simple: I would like my compilation to fail with an error if there is a warning. Yes, the famous TreatWarningsAsErrors...

我想要做的很简单:如果有警告,我希望我的编译失败并出现错误。是的,著名的TreatWarningsAsErrors...

I configured it in my C# project properties

我在我的 C# 项目属性中配置了它

treat warnings as errors

将警告视为错误

This results in the expected TreatWarningsAsErrorssection in my csproj:

这导致TreatWarningsAsErrors我的 csproj中的预期部分:

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

So far so good, if I add an useless privatevariable in my code, it results in a compilation error:

到目前为止private一切顺利,如果我在代码中添加一个无用的变量,则会导致编译错误:

private int unused;

Error 3 Warning as Error: The field 'XXXX.unused' is never used

错误 3 警告为错误:从未使用字段“XXXX.unused”

But the whole problem is, I can't make it work for assembly reference issues. If I have a reference to an unknown assembly, the compiler (either devenv or msbuild) throws a warning, but I want an error instead.

但整个问题是,我无法使其适用于程序集参考问题。如果我引用了一个未知程序集,编译器(devenv 或 msbuild)会抛出警告,但我想要一个错误。

Ultimately, I'm trying to configure a gated check-in TFS build configuration, so TFS would reject a commit in case there is a "The referenced component 'XXXX' could not be found." warning. Something simpler than modifying the build process template would be great.

最终,我正在尝试配置一个门控签入 TFS 构建配置,因此 TFS 将拒绝提交,以防出现“找不到引用的组件‘XXXX’。”警告。比修改构建过程模板更简单的东西会很棒。

采纳答案by KMoraz

MSBuild warnings (all start with MSB*) as opposed to CSC warnings cannot be suppressed nor promoted to errors. For the reason the ResolveAssemblyReferencetask prints its messages on the fly and does not aggregate any of them.

MSBuild 警告(均以 MSB* 开头)与 CSC 警告相反,无法抑制或提升为错误。出于这个原因,ResolveAssemblyReference任务会即时打印其消息,并且不会聚合任何消息。

The only feasible solution is reading the MSBuild log files created during the TFS build. I think the most elegant solution is to implement a custom Build CodeActivity. The following is a simple activity that will output to results any files containing a given SearchString:

唯一可行的解​​决方案是读取在 TFS 构建期间创建的 MSBuild 日志文件。我认为最优雅的解决方案是实现自定义 Build CodeActivity。以下是一个简单的活动,它将输出包含给定的任何文件的结果SearchString

using System;
using System.Activities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.Build.Client;

namespace MyBuildActivities.FileSystem
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class ReadStringFromFile : CodeActivity
    {
        [RequiredArgument]
        public InArgument<IEnumerable<string>> Files { get; set; }

        [RequiredArgument]
        public InArgument<string> SearchString { get; set; }

        public OutArgument<string> Result { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            var files = context.GetValue(Files);
            var searchString = context.GetValue(SearchString);

            var list =
                (files.Where(file => File.ReadAllText(file).Contains(searchString))
                    .Select(file => string.Format("{0} was found at {1}", searchString, file))).ToList();

            if(list.Count > 0)
                Result.Set(context, string.Join(Environment.NewLine, list));
        }
    }
}

Declared in the build process template like so:

在构建过程模板中声明如下:

xmlns:cfs="clr-namespace:MyBuildActivities.FileSystem;assembly=MyBuildActivities"

Invoked just at the end of the Compile and Test for Configurationsequence:

仅在Compile and Test for Configuration序列末尾调用:

<Sequence DisplayName="Handle MSBuild Errors">
         <Sequence.Variables>
                 <Variable x:TypeArguments="scg:IEnumerable(x:String)" Name="logFiles" />                                                                                                                 
                 <Variable x:TypeArguments="x:String" Name="readStringFromFileResult" />
         </Sequence.Variables>
         <mtbwa:FindMatchingFiles DisplayName="Find Log Files" MatchPattern="[String.Format(&quot;{0}\**\*.log&quot;, logFileDropLocation)]" Result="[logFiles]" mtbwt:BuildTrackingParticipant.Importance="Low" />
         <cfs:ReadStringFromFile Files="[logFiles]" SearchString="MSB3245" Result="[readStringFromFileResult]" />
         <mtbwa:WriteBuildMessage DisplayName="Write Result" Message="[readStringFromFileResult]" Importance="[Microsoft.TeamFoundation.Build.Client.BuildMessageImportance.High]" />
         <If Condition="[readStringFromFileResult.Count > 0]" DisplayName="If SearchString Was Found" mtbwt:BuildTrackingParticipant.Importance="Low">
                 <If.Then>
                          <Throw DisplayName="Throw Exception" Exception="[New Exception(readStringFromFileResult)]" mtbwt:BuildTrackingParticipant.Importance="Low" />
                 </If.Then>
         </If>                                                                                                              
</Sequence>

I've tested this on TFS 2012 though it should work for TFS 2010 as well.

我已经在 TFS 2012 上对此进行了测试,尽管它也适用于 TFS 2010。

回答by Richard Szalay

MSBuild 15 now supports a /warnaserrorflag, which forces MSBuildwarnings to be treated as errors.

MSBuild 15 现在支持一个/warnaserror标志,该标志强制将MSBuild警告视为错误。

MSBuild 15 is intalled with Visual Studio 2017 but can also be downloaded from GitHub

MSBuild 15 与 Visual Studio 2017 一起安装,但也可以从 GitHub 下载

This GitHub issueexplains why it cannot be set via an MSBuild property (tl;dr a property is too late)

这个 GitHub 问题解释了为什么它不能通过 MSBuild 属性设置(tl;dr 属性太晚了)