Error cs0579 повторяющийся атрибут system reflection assemblyversionattribute

Building a library project fails with error CS0579 (duplicate attribute) with library projects with AssemblyVersionAttribute (or other assembly attributes) specified. Adding (for example) <Gener...

Comments

@frankbuckley

@frankbuckley
frankbuckley

changed the title
dotnet build results in error CS0579 duplicate attributes with library projects with AssemblyVersionAttribute (and others) specified

dotnet build results in error CS0579 duplicate attributes with AssemblyVersionAttribute (and others) specified

Nov 19, 2016

Arkatufus

referenced
this issue
in Arkatufus/akka.net

May 10, 2017

@Arkatufus

Aaronontheweb

referenced
this issue
in akkadotnet/akka.net

May 22, 2017

@Arkatufus

@Aaronontheweb

…ary.TryGetValue() (#2651)

* Change all Dictionary.ContainsKey(key) + Dictionary[key] combination to Dictionary.TryGetValue(key, out value)

* Shuffle the code a bit so it makes more sense.

* Workaround for dotnet/cli#4783 (https://github.com/dotnet/cli/issues/4783)

* Use new C# 7.0 out variable feature

* Code formatting
- Remove curly braces from single line if statements
- Add new line to single line if and foreach statements

* Use expression body in PersistentFSMBase.SetStateTimeout

* Fix some overzealous curly cleanup

* Fix wrong conditional

* Change all out variable type to var

marcpiechura

referenced
this issue
in marcpiechura/akka.net

May 29, 2017

@Arkatufus

@marcpiechura

…ary.TryGetValue() (akkadotnet#2651)

* Change all Dictionary.ContainsKey(key) + Dictionary[key] combination to Dictionary.TryGetValue(key, out value)

* Shuffle the code a bit so it makes more sense.

* Workaround for dotnet/cli#4783 (https://github.com/dotnet/cli/issues/4783)

* Use new C# 7.0 out variable feature

* Code formatting
- Remove curly braces from single line if statements
- Add new line to single line if and foreach statements

* Use expression body in PersistentFSMBase.SetStateTimeout

* Fix some overzealous curly cleanup

* Fix wrong conditional

* Change all out variable type to var

zubialevich

referenced
this issue
in zubialevich/InfoBot-Rest

Jun 5, 2017

Aaronontheweb

referenced
this issue
in Aaronontheweb/akka.net

Jun 28, 2017

@Arkatufus

@Aaronontheweb

…ary.TryGetValue() (akkadotnet#2651)

* Change all Dictionary.ContainsKey(key) + Dictionary[key] combination to Dictionary.TryGetValue(key, out value)

* Shuffle the code a bit so it makes more sense.

* Workaround for dotnet/cli#4783 (https://github.com/dotnet/cli/issues/4783)

* Use new C# 7.0 out variable feature

* Code formatting
- Remove curly braces from single line if statements
- Add new line to single line if and foreach statements

* Use expression body in PersistentFSMBase.SetStateTimeout

* Fix some overzealous curly cleanup

* Fix wrong conditional

* Change all out variable type to var

juancarlostong

referenced
this issue
in optimizely/csharp-sdk

Mar 11, 2019

@juancarlostong

.csproj for NetStandard16 previously did not include AssemblyInfo.cs
which contains versioning information. Because of this, it used an
automatically generated one similar to the one described here:
https://github.com/dotnet/cli/issues/4783#issuecomment-382695175
We now provide the AssemblyInfo.cs to include during the build and
explicitly tell it not to autogenerate.

juancarlostong

referenced
this issue
in optimizely/csharp-sdk

Mar 29, 2019

@juancarlostong

.csproj for NetStandard16 previously did not include AssemblyInfo.cs
which contains versioning information. Because of this, it used an
automatically generated one similar to the one described here:
https://github.com/dotnet/cli/issues/4783#issuecomment-382695175
We now provide the AssemblyInfo.cs to include during the build and
explicitly tell it not to autogenerate.

juancarlostong

referenced
this issue
in optimizely/csharp-sdk

Mar 29, 2019

@juancarlostong

* fix(versioning): NetStandard16

.csproj for NetStandard16 previously did not include AssemblyInfo.cs
which contains versioning information. Because of this, it used an
automatically generated one similar to the one described here:
https://github.com/dotnet/cli/issues/4783#issuecomment-382695175
We now provide the AssemblyInfo.cs to include during the build and
explicitly tell it not to autogenerate.

* use own AssmeblyInfo.cs

* use full path

* better path

ecampidoglio

referenced
this issue
in cake-contrib/Cake.Curl

May 15, 2019

@ecampidoglio

Since the assembly metadata is specified in the project file,
we don't want MSBuild to auto-generate the AssemblyInfo.cs files because
that will result in a compilation error (dotnet/cli#4783).

@msftgits
msftgits

transferred this issue from dotnet/cli

Jan 31, 2020

Smilefounder

added a commit
to mixcore/mix.core
that referenced
this issue

Jul 25, 2021

@Smilefounder

ref: dotnet/sdk#7207
added <GenerateAssemblyInfo>false</GenerateAssemblyInfo>

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)

Содержание

  1. CS0579 Duplicate Attribute Error with .NET Core
  2. Problem description
  3. tl;dr Solution
  4. Details
  5. dotnet test result an error CS0579: Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ #4837
  6. Comments
  7. build error from artifact (Duplicate attribute in AssemblyInfo.cs) #93
  8. Comments
  9. Дублировать атрибут AssemblyVersion
  10. 29 ответы

CS0579 Duplicate Attribute Error with .NET Core

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:

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.

Источник

dotnet test result an error CS0579: Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ #4837

Hi,
When building my project under Azure Devops yaml pipeline, if I launch unit test in my Dockerfile, I get the following :
error CS0579: Duplicate ‘System.Reflection.AssemblyCompanyAttribute’

The project is like organised this way

So my Unit test (xUnit) project is under tests folder of my main project within the same repository.

My Dockerfile used for my CICD is

I both ITF.Microservices.Ordering.csproj and ITF.Microservices.Ordering.UnitTests.csproj I added the following to get rid of Duplicate errors.

Under Azure Devops I use the following pipeline

And the following build_deploy.yml template

The pipeline does build and publish the release correctly, but when I require dotnet test instruction from the Dockerfile, the tests are played and published

But it ended with an error

Full error line here
obj/Release/netcoreapp3.1/.NETCoreApp,Version=v3.1.AssemblyAttributes.cs(4,12): error CS0579: Duplicate ‘global::System.Runtime.Versioning.TargetFrameworkAttribute’ attribute [/src/src/ITF.Microservices.Ordering/ITF.Microservices.Ordering.csproj]

When I remove the dotnet test from the Dockerfile instruction, everything works fine

Some people seem to face the same problem as me
https://stackoverflow.com/a/62021598/4734707

The text was updated successfully, but these errors were encountered:

Источник

build error from artifact (Duplicate attribute in AssemblyInfo.cs) #93

.NET Core Version: (e.g. 3.0 Preview1, or daily build number, use dotnet —info )
3.0.100-preview-009750

Windows version: ( winver )
Version 1809 (OS Build 17763.134)

Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:

When trying to build a basic WPF project for dotnet core 3.0 I get multiple duplicate attribute errors that appear to be from a temporary file ( objDebugnetcoreapp3.0NetCoreWpf_xnekjbde_wpftmp.AssemblyInfo.cs ) conflicting with the actual AssemblyInfo.cs file

To get this error, after a fresh install of Visual Studio 2019 preview 1 I tried to open and build a wpf dotnet core project modified using Brian Lagunis’s instructions from his blog post here. The project is empty (was generated in Visual Studio 15.9.3)

Actual behavior:
6 duplicate attribute errors fail the build.
CS0579 Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute
CS0579 Duplicate ‘System.Reflection.AssemblyConfigurationAttribute’ attribute
CS0579 Duplicate ‘System.Reflection.AssemblyFileVersionAttribute’ attribute
CS0579 Duplicate ‘System.Reflection.AssemblyProductAttribute’ attribute
CS0579 Duplicate ‘System.Reflection.AssemblyTitleAttribute’ attribute
CS0579 Duplicate ‘System.Reflection.AssemblyVersionAttribute’ attribute

Expected behavior:
No duplicate attribute errors occur unless there are duplicate attributes in my project, in which case the error message should point to the human-made code where the error occurs.

The text was updated successfully, but these errors were encountered:

Источник

Дублировать атрибут AssemblyVersion

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

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

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

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

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

просто предположение, но вы пытались закрыть и снова открыть решение? может это решит? — Stefto

Я использую версию Visual Studio 2017 Community на Mac. У меня было консольное приложение, а затем я добавил ссылку на новый проект библиотеки классов. Эти ошибки начали появляться, когда я сделал сборку. Все, что я сделал, это удалил ссылку на проект библиотеки классов, а затем добавил ее обратно, и ошибки исчезли. — Flea

29 ответы

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

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

Да, это сработало для меня, удаления папок obj и bin было недостаточно. — Ник Йозевски

К сожалению, каждый раз, когда я меняю .csproj файл, используя его страницы свойств (Application, Build, Build Events и т. д.), PropertyGroup с GenerateAssemblyInfo исчезает :-(- Пало Мраз

Переместите его в файл Directory.Build.props — Bryan

Возможны ли какие-либо риски или отрицательный результат при использовании этого решения? — Маркоулсон

Отлично устранил мою проблему! — Дэниел Маклин

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

Итак, не должен ли процесс сборки перезаписывать существующую версию AssemblyVersion вместо создания новой записи? Я знаю, что наш процесс сборки делает это, но мне любопытно, почему он не перезаписывает существующий. Это плохо реализовано или это ограничение? — Амира

Я думаю, что для сборок .net лучше всего использовать метод внедрения версии. Но это отдельная история. В вашем случае проблема заключается в том, что существуют разные способы предоставления версий сборки через параметры сборки командной строки и через AssemblyInfo.cs, и вы должны убедиться, что используется только один метод, поскольку дублирование атрибутов является ошибкой компиляции .net. — Луки

Удаление файла AssemblyInfo.cs устранило мою проблему. — Сануши Сальгадо

При преобразовании старого проекта в .NET Core большую часть информации, которая была в AssemblyInfo.cs, теперь можно установить в самом проекте. Откройте свойства проекта и выберите вкладку Package, чтобы увидеть новые настройки.

  • удалить конфликтующие элементы из файла AssemblyInfo.cs,
  • полностью удалить файл или
  • отключить GenerateAssemblyInfo (как предлагается в еще один ответ Сергея Семенова)

Я считаю более интуитивным и более «Visual Studio» указать эти атрибуты в проекте ( .csproj ), поскольку они являются метаданными, а не кодом, описывающим реальную логику. Надеюсь в будущем все можно будет уточнить в проекте! (В настоящее время я не могу указать видимость COM, поэтому я оставляю AssemblyInfo.cs .) — Франклин Ю

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

Я попробовал это, и это ничего не изменило в моем случае 🙁 — Герцен

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

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

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

ответ дан 12 дек ’17, 12:12

Я удалил подпроект из решения, но подкаталог и файлы все еще находились там. Их удаление окончательно решило проблему. — tobbenb3

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

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

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

В проекте уже должен быть файл AssemblyInfo.cs:

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

ответ дан 16 апр.

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

AssemblyInfo.cs

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

ответ дан 28 апр.

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

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

ответ дан 23 мар ’17, в 16:03

Точно так же у меня был файл .csproj (A) внутри другой папки, принадлежащей другому .csproj (B). — Тейлорсвифтфан

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

Так как они теперь хранятся в проекте.

ответ дан 19 окт ’17, 08:10

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

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

ответ дан 25 дек ’18, 02:12

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

Очистка ветки разрешила это для меня:

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

Создан 15 июля ’21, 17:07

Я нашел этот ответ на msdn, который объясняет, как пометить файл как содержимое, а затем скопировать в вывод = если новее. См. статью ниже:

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

ответ дан 17 окт ’19, 09:10

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

Это мне очень помогло! Один проект ссылался на другой как на зависимость во время сборки, но ошибка в csproj привела к тому, что папки obj были разными, что привело к этой ошибке. — Чад Джессап

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

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

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

ответ дан 16 мар ’17, в 10:03

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

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

ответ дан 17 мар ’20, в 21:03

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

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

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

ответ дан 01 апр.

Я получил ошибку сразу после перехода с .NET Framework на .NET Core. У меня есть 2 проекта библиотеки классов в моем решении Visual Studio. Я понял, что в одном из проектов есть файл с именем AssemblyInfo.cs в то время как другой проект не имеет файла. Файл находится под Properties папка. Я просто удаляю папку «Свойства» и все работает нормально.

ответ дан 25 дек ’20, 03:12

Я боролся с этой проблемой, но мою проблему было решить намного проще.

Я скопировал папку OBJ с именем «OBJ___», чтобы выполнить некоторые тесты компиляции.

Итак, я не знаю почему, эта папка также компилировалась, создавая дублирование атрибутов сборки.

Я просто удалил папку «OBJ___» и смог успешно скомпилировать.

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

Мы попытались удалить папки bin и obj и сделать git clean -xfd но ни один из них не решил проблему. В этом случае начало с чистой копии репо помогло.

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

ответ дан 02 окт ’21, 22:10

В моем случае один из моих коллег удалил консольное приложение, используемое для тестирования, которое было помещено в тот же каталог, что и наш API, а затем передано в Git. Когда я позже вытащил из Git, само консольное приложение, конечно, исчезло, но его папки bin и obj все еще были там, в результате чего файл AssemblyInfo.cs присутствовал как в корневом каталоге приложения, так и в подкаталоге для старого консольного приложения. Простое удаление папок bin и obj для старого консольного приложения решило проблему.

Я получил эти ошибки, потому что я пытался временно переименовать папку obj в obj_, а затем он автоматически включается в проект. Потом сборка.cs в ней стала биться с правильной в папке obj сгенерированной позже.

ответ дан 23 дек ’21, 07:12

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

Урок: Предположим, что все лгут.

ответ дан 18 окт ’21, 20:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c# compiler-errors or задайте свой вопрос.

Источник

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)

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.

Problem

You’re trying to add the AssemblyVersion attribute to your project, like this:

using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

Code language: C# (cs)

And you get the following compiler errors:

Error CS0579 Duplicate ‘AssemblyVersion’ attribute

Error CS0579 Duplicate ‘AssemblyFileVersion’ attribute

But you don’t see these attributes anywhere else in your project.

Solution

The problem is Visual Studio auto-generates the assembly info by default.

To turn this off, put the following in your .csproj file:

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

Code language: HTML, XML (xml)

Where is the auto-generated assembly info?

My assembly is called DupeAssemblyVersion and I’m targeting .NET Core 3.1. So the auto-generated assembly info file is here: objDebugnetcoreapp3.1DupeAssemblyVersion.AssemblyInfo.cs.

Here’s what this file looks like:

//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("DupeAssemblyVersion")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("DupeAssemblyVersion")] [assembly: System.Reflection.AssemblyTitleAttribute("DupeAssemblyVersion")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.

Code language: C# (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.


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

ошибка 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.

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


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

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

Понравилась статья? Поделить с друзьями:
  • Error cs0535 unity
  • Error cs0433 the type exists in both
  • Error cs0305 using the generic method group getcomponent requires 1 type arguments
  • Error cs0246 unity3d как исправить
  • Error cs0246 unity как исправить