Ошибка cs0579 повторяющийся атрибут system reflection assemblycompanyattribute

When you create a project, Visual Studio sets it up to compile & generate a corresponding assembly. Each project generates 1 assembly, and so each has a corresponding assembly configuration to generate its assembly from.

The problem is when you create more than one project that each can generate their own assembly, and then include one of these projects in the other.

In this scenario, Visual Studio gets confused and doesn’t know which config file to go off of to generate the single assembly for the project — it finds the second assembly configuration in the included project and says «HEY, DUPLICATE! You’ve given me two sets of instructions for generating my assembly!»

But sometimes you still want the included project to be able to generate an assembly on it’s own, but not when it is being included in another project.

To obtain this, one solution is to add conditional defines to the including project (found in project Properties). Then change the assembly config in the included project to look for this conditional define. If it is defined (by the including project), then the config can skip over it’s content — this will result in only 1 config found by VS — the one from the including project — problem solved!

Steps Below (screenshots included)

Step 1: Select the including/container Project > Right Click > Properties

Project properties (screenshot)

Step 2: Navigate to Build > General > Conditional compilation symbols

Add your conditional defines as shown:

Conditional compilation symbols (screenshot)

Step 3: Use conditional defines in the included project AssemblyInfo.cs

Using conditional defines (screenshot)

UPDATED: 2020-12-23

I’ll leave the below for posterity, but recently I came across the real reason for the error. In this issue it was pointed out that your .net core solutions have to be structured in a particular way. Specifically, make sure that you do not create projects in the same directory as your main project.


Problem description

I recently started working on my first .NET Core project and quickly ran into a problem. After adding a class library project, the second time I ran dotnet run I received the following errors:

error CS0579: Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyConfigurationAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyFileVersionAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyInformationalVersionAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyProductAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyTitleAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyVersionAttribute’ attribute

tl;dr Solution

My Google-fu revealed the solution buried in a GitHub issue thread. Add the following line to your *.csproj files:

<GenerateAssemblyInfo>false</GenerateAssemblyInfo>

As the name indicates, this will prevent the build process from generating the AssemblyInfo.cs file in project obj directories, thus preventing the duplicate attribute conflict.

Details

Disclaimer: I am far from a .NET expert so there is probably more to this story.

The error is a result of the build process generating AssemblyInfo.cs files in each project obj directory. This file exists to provide MSBuild metadata about the resulting assembly that can be attached to the build artifact and utilized by anyone who wants such information. You can see your assembly info in Windows by selecting your build artifact, right click -> properties. The following shows the results with GenerateAssemblyInfo set to false. As you can see, the metadata is set to default values.

It’s not clear why the default .csproj file generated by dotnet new results in this behavior. The closest I came across was a mention of the philosophy to keep the file as terse as possible. Of course, I’m completely in support of this as .csproj tends to be a dense mess in Visual Studio. However, this particular scenario puts the onus on the developer to edit the file to eliminate an error which is almost guaranteed to occur in a project of any complexity. A better design decision would have probably been to default to not generating AssemblyInfo.cs.

@piotrpMSFT I tried suggested solution with adding Exclude to Compile section and getting following crash:

MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.Shared.FileMatcher.GetFiles(String projectDirectoryUnescaped, String filespecUnescaped, IEnumerable`1 excludeSpecsUnescaped, GetFileSystemEntries getFileSystemEntries, DirectoryExists directoryExists)
   at Microsoft.Build.Internal.EngineFileUtilities.GetFileList(String directoryEscaped, String filespecEscaped, Boolean returnEscaped, IEnumerable`1 excludeSpecsEscaped)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.IncludeOperation.SelectItems(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemOperation.Apply(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.MemoizedOperation.Apply(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemList.ComputeItems(LazyItemList lazyItemList, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemList.GetItems(ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.<>c.<GetAllItems>b__22_0(LazyItemList itemList)
   at System.Linq.Enumerable.<SelectManyIterator>d__157`2.MoveNext()
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source, Int32& length)
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.OrderedEnumerable`1.ToList()
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.GetAllItems()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Execution.ProjectInstance.Initialize(ProjectRootElement xml, IDictionary`2 globalProperties, String explicitToolsVersion, String explicitSubToolsetVersion, Int32 visualStudioVersionFromSolution, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext)
   at Microsoft.Build.Execution.ProjectInstance..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext)
   at Microsoft.Build.BackEnd.RequestBuilder.LoadProjectIntoConfiguration()
   at Microsoft.Build.BackEnd.RequestBuilder.<BuildProject>d__57.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.Build.BackEnd.RequestBuilder.<BuildAndReport>d__49.MoveNext()

MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.CommandLine.MSBuildApp.BuildProject(String projectFile, String[] targets, String toolsVersion, Dictionary`2 globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, Int32 cpuCount, Boolean enableNodeReuse, TextWriter preprocessWriter, Boolean debugger, Boolean detailedSummary)
   at Microsoft.Build.CommandLine.MSBuildApp.Execute(String[] commandLine)

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.CommandLine.MSBuildApp.BuildProject(String projectFile, String[] targets, String toolsVersion, Dictionary`2 globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, Int32 cpuCount, Boolean enableNodeReuse, TextWriter preprocessWriter, Boolean debugger, Boolean detailedSummary)
   at Microsoft.Build.CommandLine.MSBuildApp.Execute(String[] commandLine)
   at Microsoft.Build.CommandLine.MSBuildApp.Main(String[] args)

When you create a project, Visual Studio sets it up to compile & generate a corresponding assembly. Each project generates 1 assembly, and so each has a corresponding assembly configuration to generate its assembly from.

The problem is when you create more than one project that each can generate their own assembly, and then include one of these projects in the other.

In this scenario, Visual Studio gets confused and doesn’t know which config file to go off of to generate the single assembly for the project — it finds the second assembly configuration in the included project and says «HEY, DUPLICATE! You’ve given me two sets of instructions for generating my assembly!»

But sometimes you still want the included project to be able to generate an assembly on it’s own, but not when it is being included in another project.

To obtain this, one solution is to add conditional defines to the including project (found in project Properties). Then change the assembly config in the included project to look for this conditional define. If it is defined (by the including project), then the config can skip over it’s content — this will result in only 1 config found by VS — the one from the including project — problem solved!

Steps Below (screenshots included)

Step 1: Select the including/container Project > Right Click > Properties

Project properties (screenshot)

Step 2: Navigate to Build > General > Conditional compilation symbols

Add your conditional defines as shown:

Conditional compilation symbols (screenshot)

Step 3: Use conditional defines in the included project AssemblyInfo.cs

Using conditional defines (screenshot)

UPDATED: 2020-12-23

I’ll leave the below for posterity, but recently I came across the real reason for the error. In this issue it was pointed out that your .net core solutions have to be structured in a particular way. Specifically, make sure that you do not create projects in the same directory as your main project.


Problem description

I recently started working on my first .NET Core project and quickly ran into a problem. After adding a class library project, the second time I ran dotnet run I received the following errors:

error CS0579: Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyConfigurationAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyFileVersionAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyInformationalVersionAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyProductAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyTitleAttribute’ attribute
error CS0579: Duplicate ‘System.Reflection.AssemblyVersionAttribute’ attribute

tl;dr Solution

My Google-fu revealed the solution buried in a GitHub issue thread. Add the following line to your *.csproj files:

<GenerateAssemblyInfo>false</GenerateAssemblyInfo>

As the name indicates, this will prevent the build process from generating the AssemblyInfo.cs file in project obj directories, thus preventing the duplicate attribute conflict.

Details

Disclaimer: I am far from a .NET expert so there is probably more to this story.

The error is a result of the build process generating AssemblyInfo.cs files in each project obj directory. This file exists to provide MSBuild metadata about the resulting assembly that can be attached to the build artifact and utilized by anyone who wants such information. You can see your assembly info in Windows by selecting your build artifact, right click -> properties. The following shows the results with GenerateAssemblyInfo set to false. As you can see, the metadata is set to default values.

It’s not clear why the default .csproj file generated by dotnet new results in this behavior. The closest I came across was a mention of the philosophy to keep the file as terse as possible. Of course, I’m completely in support of this as .csproj tends to be a dense mess in Visual Studio. However, this particular scenario puts the onus on the developer to edit the file to eliminate an error which is almost guaranteed to occur in a project of any complexity. A better design decision would have probably been to default to not generating AssemblyInfo.cs.

@piotrpMSFT I tried suggested solution with adding Exclude to Compile section and getting following crash:

MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.Shared.FileMatcher.GetFiles(String projectDirectoryUnescaped, String filespecUnescaped, IEnumerable`1 excludeSpecsUnescaped, GetFileSystemEntries getFileSystemEntries, DirectoryExists directoryExists)
   at Microsoft.Build.Internal.EngineFileUtilities.GetFileList(String directoryEscaped, String filespecEscaped, Boolean returnEscaped, IEnumerable`1 excludeSpecsEscaped)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.IncludeOperation.SelectItems(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemOperation.Apply(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.MemoizedOperation.Apply(Builder listBuilder, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemList.ComputeItems(LazyItemList lazyItemList, ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.LazyItemList.GetItems(ImmutableHashSet`1 globsToIgnore)
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.<>c.<GetAllItems>b__22_0(LazyItemList itemList)
   at System.Linq.Enumerable.<SelectManyIterator>d__157`2.MoveNext()
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source, Int32& length)
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.OrderedEnumerable`1.ToList()
   at Microsoft.Build.Evaluation.LazyItemEvaluator`4.GetAllItems()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Execution.ProjectInstance.Initialize(ProjectRootElement xml, IDictionary`2 globalProperties, String explicitToolsVersion, String explicitSubToolsetVersion, Int32 visualStudioVersionFromSolution, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext)
   at Microsoft.Build.Execution.ProjectInstance..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, BuildParameters buildParameters, ILoggingService loggingService, BuildEventContext buildEventContext)
   at Microsoft.Build.BackEnd.RequestBuilder.LoadProjectIntoConfiguration()
   at Microsoft.Build.BackEnd.RequestBuilder.<BuildProject>d__57.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.Build.BackEnd.RequestBuilder.<BuildAndReport>d__49.MoveNext()

MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.CommandLine.MSBuildApp.BuildProject(String projectFile, String[] targets, String toolsVersion, Dictionary`2 globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, Int32 cpuCount, Boolean enableNodeReuse, TextWriter preprocessWriter, Boolean debugger, Boolean detailedSummary)
   at Microsoft.Build.CommandLine.MSBuildApp.Execute(String[] commandLine)

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Build.CommandLine.MSBuildApp.BuildProject(String projectFile, String[] targets, String toolsVersion, Dictionary`2 globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, Int32 cpuCount, Boolean enableNodeReuse, TextWriter preprocessWriter, Boolean debugger, Boolean detailedSummary)
   at Microsoft.Build.CommandLine.MSBuildApp.Execute(String[] commandLine)
   at Microsoft.Build.CommandLine.MSBuildApp.Main(String[] args)

As part of my research into IdentityServer4 I forked their samples repo, but I ran into the following issue trying to build the solution for the Client Credentials quickstart.

CS0579    Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute

CS0579    Duplicate ‘System.Reflection.AssemblyConfigurationAttribute’ attribute

CS0579    Duplicate ‘System.Reflection.AssemblyProductAttribute’ attribute

Searching the project each of these attributes only exists only in the AssemblyInfo.cs file found under properties. It turns out the file that is causing the issues only exists as a result of the build process and is found in the objDebugnetcoreapp1.1{ProjectName}.AssemblyInfo.cs file.

In this case, the client project is a console application so I created a new console application and the template no longer generates an AssemblyInfo.cs file for .NET Core. It turns out that as part of the move back to csproj most of the information that was in the AssemblyInfo.cs can now be set on the project its self. Open the project properties and select the Package tab to see the new settings.

Resolution

I found this issue on GitHub where there were a couple of options to resolve this issue which I am going to cover here plus a third option I tried not mention in the issue.

Option one is to remove the conflicting items from the AssemblyInfo.cs file. For example, the following would allow the project I am working with to build.

Before:
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Client")]
[assembly: AssemblyTrademark("")]

After:
[assembly: AssemblyTrademark("")]

Option two is to edit the csproj and turn the generation of the attributes causing the issues off.

Before:
<PropertyGroup>
  <TargetFramework>netcoreapp1.1</TargetFramework>
  <OutputType>Exe</OutputType>
</PropertyGroup>

After:
<PropertyGroup>
  <TargetFramework>netcoreapp1.1</TargetFramework>
  <OutputType>Exe</OutputType>
  <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
  <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
  <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>

The third option is to total delete the AssemblyInfo.cs file if your project doesn’t need it. This is the option I chose to go with. For a reason, you might want to keep the file around and just use option one see the “AssemblyInfo.cs is partially dead” section of this post by Muhammad Rehan Saeed. Side note: if you are interested in ASP.NET Core and you aren’t following Rehan you really should be.

Wrapping up

This is an issue that you will really only face when converting an older project to .NET Core. The fix is simple enough once you know what is going on. I opened an issue on the IdentityServer samples if you want to track if this has been fixed yet.

When you create a project, Visual Studio sets it up to compile & generate a corresponding assembly. Each project generates 1 assembly, and so each has a corresponding assembly configuration to generate its assembly from.

The problem is when you create more than one project that each can generate their own assembly, and then include one of these projects in the other.

In this scenario, Visual Studio gets confused and doesn’t know which config file to go off of to generate the single assembly for the project — it finds the second assembly configuration in the included project and says «HEY, DUPLICATE! You’ve given me two sets of instructions for generating my assembly!»

But sometimes you still want the included project to be able to generate an assembly on it’s own, but not when it is being included in another project.

To obtain this, one solution is to add conditional defines to the including project (found in project Properties). Then change the assembly config in the included project to look for this conditional define. If it is defined (by the including project), then the config can skip over it’s content — this will result in only 1 config found by VS — the one from the including project — problem solved!

Steps Below (screenshots included)

Step 1: Select the including/container Project > Right Click > Properties

Project properties (screenshot)

Step 2: Navigate to Build > General > Conditional compilation symbols

Add your conditional defines as shown:

Conditional compilation symbols (screenshot)

Step 3: Use conditional defines in the included project AssemblyInfo.cs

Using conditional defines (screenshot)

When you create a project, Visual Studio sets it up to compile & generate a corresponding assembly. Each project generates 1 assembly, and so each has a corresponding assembly configuration to generate its assembly from.

The problem is when you create more than one project that each can generate their own assembly, and then include one of these projects in the other.

In this scenario, Visual Studio gets confused and doesn’t know which config file to go off of to generate the single assembly for the project — it finds the second assembly configuration in the included project and says «HEY, DUPLICATE! You’ve given me two sets of instructions for generating my assembly!»

But sometimes you still want the included project to be able to generate an assembly on it’s own, but not when it is being included in another project.

To obtain this, one solution is to add conditional defines to the including project (found in project Properties). Then change the assembly config in the included project to look for this conditional define. If it is defined (by the including project), then the config can skip over it’s content — this will result in only 1 config found by VS — the one from the including project — problem solved!

Steps Below (screenshots included)

Step 1: Select the including/container Project > Right Click > Properties

Project properties (screenshot)

Step 2: Navigate to Build > General > Conditional compilation symbols

Add your conditional defines as shown:

Conditional compilation symbols (screenshot)

Step 3: Use conditional defines in the included project AssemblyInfo.cs

Using conditional defines (screenshot)


У меня есть проект, который генерирует следующую ошибку при компиляции:

ошибка CS0579: повторяющийся атрибут AssemblyVersion

Я проверил файл AssemblyInfo.csи похоже, что там нет дубликатов.

Я нашел эту статью в MSDN, в которой рассматривается аналогичная проблема, и следование предложению в этой статье также устраняет проблему.

Кто-нибудь может сказать мне, что здесь происходит? Это происходит только в случае наличия двух и более проектов с похожими именами классов? Или что-то еще?




Ответы:


Я также сталкивался с этой проблемой в прошлом, поэтому предполагаю, что ваш процесс сборки предоставляет информацию о сборке отдельно от обеспечения управления версиями. И это вызывает дублирование, поскольку в вашем проекте также есть эта информация в AssemblyInfo.csфайле. Так что удалите файл, и я думаю, он должен работать.





Начиная с Visual Studio 2017, еще одним решением для продолжения использования AssemblyInfo.csфайла является отключение автоматического создания информации о сборке следующим образом:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
  </PropertyGroup>
</Project>

Я лично считаю его очень полезным для проектов, которые должны поддерживать как .NET Framework, так и .NET Standard.







У меня была такая же ошибка, и в ней подчеркивались версия сборки и версия файла сборки, поэтому, прочитав ответ Luqi, я просто добавил их в качестве комментариев, и ошибка была решена

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]




В моем случае в проект случайно были добавлены временные файлы * .cs, созданные во время компиляции.

Файлы были из objDebugкаталога, поэтому их определенно не следовало добавлять в решение. *.csПодстановочные пошел немного сумасшедший и добавил их неправильно.

Удаление этих файлов устранило проблему.


В моем случае это вложенная папка в проекте, которая сама была папкой проекта:

  • файловая система:

    • c: проекты webapi wepapi.csproj
    • c: проекты webapi tests wepapitests.csproj
  • решение

    • webapi (папка и проект)
      • тесты (папка)
    • тесты (папка и проект)

Затем мне пришлось удалить подпапку «тесты» из проекта «webapi».


Для меня это было то, что AssembyInfo.cs и SolutionInfo.cs имели разные значения. Так что проверьте и эти файлы. Я только что удалил версию с одного из них.


Моя ошибка возникла из-за того, что каким-то образом внутри моей папки контроллеров была создана папка obj. Просто поищите в своем приложении строку внутри Assemblyinfo.cs. Возможно где-то есть дубликат.



Еще одно решение при обновлении ядра до VS2017 — удалить их в файле properties assemblyinfo.cs.

Поскольку они сейчас хранятся в проекте.


Обычно это происходит со мной, если я скомпилировал проект в Visual Studio 2017, а затем попытаюсь перестроить и запустить его с .NET Core с помощью команды командной строки «dotnet run».

Простое удаление всех папок «bin» и «obj» — как внутри «ClientApp», так и непосредственно в папке проекта — позволило команде .NET Core «dotnet run» успешно перестроить и запустить.


Я столкнулся с тем же, когда попытался добавить инструмент GitVersion для обновления моей версии в AssemblyInfo.cs. Используйте проект VS2017 и .NET Core. Так что я просто смешал оба мира. Мой AssemblyInfo.cs содержит только информацию о версии, сгенерированную инструментом GitVersion, мой csproj содержит оставшиеся вещи. Обратите внимание: я не использую, <GenerateAssemblyInfo>false</GenerateAssemblyInfo>я использую только атрибуты, относящиеся к версии (см. Ниже). Подробнее здесь AssemblyInfo properties .

AssemblyInfo.cs

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+13.Branch.master.Sha.119c35af0f529e92e0f75a5e6d8373912d457818")]

my.csproj содержит все, что связано с другими атрибутами сборки:

<PropertyGroup>
...
<Company>SOME Company </Company>
<Authors>Some Authors</Authors>
<Product>SOME Product</Product>
...
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>

csproj сопоставляется с вкладкой пакета в свойствах проекта


Здесь в проекте уже должен быть файл AssemblyInfo.cs:
введите описание изображения здесь

Чтобы решить: — Удалите любой AssemblyInfo.cs



У меня была эта проблема, когда мой основной проект находился в той же папке, что и решение, тогда у меня был отдельный проект в том же решении, расположенный во вложенной папке, и этот отдельный проект использовал основной проект в качестве ссылки. Это привело к тому, что основной проект обнаружил подпапки bin и obj, которые создавали повторяющиеся ссылки.



Если у вас возникла эта проблема в конвейере сборки в Azure DevOps, попробуйте указать действие сборки как «Содержимое» и «Копировать в выходной каталог», равное «Копировать, если новее» в свойствах файла AssembyInfo.cs.


Моя ошибка заключалась в том, что я также ссылался на другой файл в моем проекте, который также содержал значение для атрибута AssemblyVersion. Я удалил этот атрибут из одного файла, и теперь он работает правильно.

Главное — убедиться, что это значение не объявляется более одного раза в любом файле вашего проекта.


Отредактируйте AssemblyInfo.cs и #if! NETCOREAPP3_0 … #endif

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

#if !NETCOREAPP3_0  

[assembly: AssemblyTitle(".Net Core Testing")]
[assembly: AssemblyDescription(".Net Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(".Net Core")]
[assembly: AssemblyCopyright("Copyright ©")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("000b119c-2445-4977-8604-d7a736003d34")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

#endif


Я получил эту ошибку, когда поместил 2 проекта в один каталог. Если у меня есть каталог с решением, и я помещаю в него отдельный каталог Web и Data, он компилируется правильно.


objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(15,12): error CS0579: Duplicate 'System.Reflection.AssemblyConfigurationAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]
objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(16,12): error CS0579: Duplicate 'System.Reflection.AssemblyFileVersionAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]
objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(17,12): error CS0579: Duplicate 'System.Reflection.AssemblyInformationalVersionAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]
objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(18,12): error CS0579: Duplicate 'System.Reflection.AssemblyProductAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]
objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(19,12): error CS0579: Duplicate 'System.Reflection.AssemblyTitleAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]
objDebugnetstandard2.0PacktLibrary.AssemblyInfo.cs(20,12): error CS0579: Duplicate 'System.Reflection.AssemblyVersionAttribute' attribute [c:UsersJohn_Tosh1DocumentsC#8.0and.NetCore3.0CodeChapter05PacktLibraryPacktLibrary.csproj]

Я считаю, что моя папка библиотеки была повреждена из-за непреднамеренного создания другой библиотеки классов. Я удалил библиотеку и все связанные файлы, но проблема не исчезла. Я нашел обходной путь, удалив ВСЕ папки bin и obj в каталоге. Раньше сборка проходила нормально, но была обнаружена подпапка с тем же файлом assemblyinfo.cs.


Эта проблема является конфликтом ссылок, который в основном характерен для VS 2017.

Я решил эту же ошибку, просто закомментировав строки 7-14, а также коды версий сборки внизу страницы на AssemblyInfo.cs.

Он удалил все повторяющиеся ссылки, и проект можно было построить снова.


Мне пришлось удалить все репо и клонировать новую копию, чтобы заставить ее работать.

Я попытался удалить все упомянутые выше файлы, но это не сработало.

  • Remove From My Forums
  • Question

  • I have created a new GAT project. Removed all the existing projects which are shown by default in the Project.

    I am adding a new project under Templates/Solutions/Projects/MyClassProject

    This folder has a file Properties/AssemblyInfo.cs. When am compiling my solution I ma getting the following compile errors

    Can someone help me understand why is this compiler errors seen? This AssemblyInfo.cs if my GAT project’s file and it seems to be clashing with Templates/Solutions/Projects/MyClassProject/Properties/AssemblyInfo.cs file.

    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(31,12): error CS0579: Duplicate ‘AssemblyVersion’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(20,12): error CS0579: Duplicate ‘ComVisible’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(15,12): error CS0579: Duplicate ‘AssemblyCulture’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(14,12): error CS0579: Duplicate ‘AssemblyTrademark’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(13,12): error CS0579: Duplicate ‘AssemblyCopyright’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(12,12): error CS0579: Duplicate ‘AssemblyProduct’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(11,12): error CS0579: Duplicate ‘AssemblyCompany’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(10,12): error CS0579: Duplicate ‘AssemblyConfiguration’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(9,12): error CS0579: Duplicate ‘AssemblyDescription’ attribute
    C:TempForDeleteRndTest_GuidancePackageMyApplicationPackageMyApplicationPackagePropertiesAssemblyInfo.cs(8,12): error CS0579: Duplicate ‘AssemblyTitle’ attribute

Answers

  • This is because you haven’t marked the .cs files you added as content files. You need to make sure the .cs files you add to the «Templates» folder are properly marked as «Build Action=Content» and «Copy To Output Directory=Copy If Newer» so they don’t get compiled with your solution (and classes don’t clash).

    In GAT, there is a recipe for automating this setting, if you right-click on the «Templates» folder you should see it, I just don’t remember the exact name for it right now, sorry.

    -vga.

  • When you right click on the «Templates» folder of your guidance package project you should get a menu option named «Set Content Files Build Properties», this is the recipe that will automatically set proper build properties for all the content files within that folder. If this option doesn’t appear please make sure that GAT is enabled for the solution you’re working on (go to Tools->Guidance Package Manager->Enable/Disable Packages and make sure Guidance Package Development is checked).

    If you want to do this manually, you need to go to each file located within «Templates» folder, look at its properties (press F4) and set its «Build Action» property to «Content» and its «Copy To Output Directoy» as «Copy if newer».

    HTH,
    -vga.

As part of my research into IdentityServer4 I forked their samples repo, but I ran into the following issue trying to build the solution for the Client Credentials quickstart.

CS0579    Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute

CS0579    Duplicate ‘System.Reflection.AssemblyConfigurationAttribute’ attribute

CS0579    Duplicate ‘System.Reflection.AssemblyProductAttribute’ attribute

Searching the project each of these attributes only exists only in the AssemblyInfo.cs file found under properties. It turns out the file that is causing the issues only exists as a result of the build process and is found in the objDebugnetcoreapp1.1{ProjectName}.AssemblyInfo.cs file.

In this case, the client project is a console application so I created a new console application and the template no longer generates an AssemblyInfo.cs file for .NET Core. It turns out that as part of the move back to csproj most of the information that was in the AssemblyInfo.cs can now be set on the project its self. Open the project properties and select the Package tab to see the new settings.

Resolution

I found this issue on GitHub where there were a couple of options to resolve this issue which I am going to cover here plus a third option I tried not mention in the issue.

Option one is to remove the conflicting items from the AssemblyInfo.cs file. For example, the following would allow the project I am working with to build.

Before:
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Client")]
[assembly: AssemblyTrademark("")]

After:
[assembly: AssemblyTrademark("")]

Option two is to edit the csproj and turn the generation of the attributes causing the issues off.

Before:
<PropertyGroup>
  <TargetFramework>netcoreapp1.1</TargetFramework>
  <OutputType>Exe</OutputType>
</PropertyGroup>

After:
<PropertyGroup>
  <TargetFramework>netcoreapp1.1</TargetFramework>
  <OutputType>Exe</OutputType>
  <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
  <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
  <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>

The third option is to total delete the AssemblyInfo.cs file if your project doesn’t need it. This is the option I chose to go with. For a reason, you might want to keep the file around and just use option one see the “AssemblyInfo.cs is partially dead” section of this post by Muhammad Rehan Saeed. Side note: if you are interested in ASP.NET Core and you aren’t following Rehan you really should be.

Wrapping up

This is an issue that you will really only face when converting an older project to .NET Core. The fix is simple enough once you know what is going on. I opened an issue on the IdentityServer samples if you want to track if this has been fixed yet.

Понравилась статья? Поделить с друзьями:
  • Ошибка cs0200 невозможно присвоить значение свойству или индексатору
  • Ошибка cs0165 использование локальной переменной которой не присвоено значение
  • Ошибка cs0161 не все пути к коду возвращают значение
  • Ошибка cs0120 для нестатического поля метода или свойства
  • Ошибка cs0106 модификатор public недопустим для этого элемента