Как создать gitignore visual studio
Какие файлы следует включать .gitignore при использовании Git вместе с Visual Studio Solutions ( .sln ) и Projects?
Я был бы осторожен, игнорируя .exe и .pdb, вы можете случайно проигнорировать инструменты, которые вы храните с вашим источником (nant, nunit gui и т. Д.).
Пожалуйста, обрати внимание. Этот файл содержит запись, позволяющую игнорировать опубликованные файлы. Как бы то ни было, это правило игнорирует любую папку, которую вы назвали «Опубликовать», и, следовательно, игнорирует все, что у вас есть под ней. Он не предназначен специально для вывода Visual Studio «Публикация». Он проигнорирует это, но также и другие вещи.
@starfighterxyz, если вы считаете, что в gitignore есть ошибка, я бы рекомендовал создать запрос на перенос.
Ну, я не знаю (достаточно?), Чтобы сказать, что это ошибка. Я просто использовал Publish / как имя контроллера и как имена папок проекта. Думаю, это просто крайний случай. Просто то, что сэкономит несколько часов своей жизни :)
Любая идея, почему файлы Windows, такие как Thumbs.db и Desktop.ini, не указаны в файле по указанной ссылке?
20.08.2014 вот файл, созданный для Visual Studio + Windows.
В идеале внутри файла должна быть лицензия. (В идеале это была бы лицензия, не вызывающая вопросов в корпоративной среде.)
@PerLundberg Одна из причин, по которой стоит задуматься, заключается в том, что вы можете настроить стандартные параметры форматирования проекта и т. Д. И сохранить файлы конфигурации вместе с проектом. Если это находится в git, всем, кто использует Resharper, будет проще поддерживать согласованный формат проекта.
Для тех, кто интересуется тем, что, по мнению Microsoft, должно быть включено в gitignore, вот вариант по умолчанию, который Visual Studio 2013 RTM автоматически генерируется при создании нового репозитория Git:
Хотя вы должны сохранить файл NuGet packages.config, вы должны исключить папку пакетов:
Обычно я не храню двоичные файлы или что-либо, созданное из моего источника, в системе управления версиями. Однако по этому поводу существуют разные мнения. Если это упростит вашу систему сборки, сделайте это! Однако я бы сказал, что вы не управляете версиями этих зависимостей, поэтому они просто займут место в вашем репозитории. На мой взгляд, лучшим решением является хранение двоичных файлов в центральном месте, а затем использование файла packages.config для указания необходимой версии.
кто-нибудь хочет уточнить, почему вы хотите исключить папку пакетов? Разве нет смысла включать пакеты для сервера сборки, чтобы они имели зависимости?
Стоит отметить, что команда NuGet реализовала функцию «восстановления пакета» именно для этой проблемы. На сайте NuGet есть документ, в котором объясняется эта функция и описывается, как ее использовать в Visual Studio.
Если вы игнорируете пакеты и используете восстановление пакетов nuget, полезно разрешить nuget.exe. Когда кто-то загружает, это помогает VS узнать, что функция включена для решения: !NuGet.exe
Тем из вас, кто использует AppHarbor, стоит отметить, что исключение папки пакетов приведет к сбою развертывания вашей сборки :)
Я понимаю, что это старый вопрос, но я все еще делюсь информацией. В Visual Studio 2017 вы можете просто щелкнуть правой кнопкой мыши файл решения и выбрать Добавить решение в систему управления версиями.
Это добавит два файла в исходную папку.
Это самый простой способ.
Как вы просматриваете эти файлы в Visual Studio? они создаются в папке решения, но не отображаются в проводнике решений.
Я предпочитаю исключать вещи по мере необходимости. Вы же не хотите, чтобы дробовик исключал все, в названии которого есть строка «bin» или «obj». По крайней мере, обязательно ставьте перед ними косую черту.
Вот с чего я начинаю свой проект VS2010:
И только потому, что я использую ReSharper, еще и это:
Согласен. Также это касается «отладки». Добавьте к этому завершающую косую черту, чтобы не игнорировать файлы с отладкой в имени.
В Visual Studio 2015 Team Explorer> Локальные репозитории Git> Проект> Настройки> Git> Настройки репозитория> Игнорировать файлы атрибутов. Вы можете добавить файл .gitignore, элементы которого должны игнорироваться в решениях Visual Studio по умолчанию.
В Visual Studio 2015 с обновлением 3 и с расширением Git, обновленным на сегодняшний день (2016-10-24), .gitignore, созданный Visual Studio, выглядит следующим образом:
Добавлен InstallShield, игнорирующий при развертывании сборки. InstallShield - это новое направление, в котором Microsoft движется по Visual Studio Installer, поэтому мы начали использовать его во всех новых проектах. Эта добавленная строка удаляет установочные файлы SingleImage. Другие типы InstallShield могут включать в себя, среди прочего, распространение DVD. Вы можете добавить эти имена каталогов или просто [Ee] xpress /, чтобы предотвратить попадание файлов развертывания InstallShield LE в репозиторий.
Я цитирую здесь комментарий Джеймса Грегори: «Я был бы осторожен, игнорируя .exe и .pdb, вы можете непреднамеренно проигнорировать инструменты, которые храните вместе с вашим источником (nant, nunit gui и т. Д.). - Джеймс Грегори, 21 мая 2010 г., 13:32 "
Просто пояснение - он фактически перемещается НАЗАД в InstallShield, который существовал до установщика VisualStudio, по крайней мере, еще в 1998 году!
Я знаю, что это старый поток, но для новых и старых, которые посещают эту страницу, есть веб-сайт gitignore.io, который может генерировать эти файлы. Найдите "visualstudio" при переходе на веб-сайт, и он сгенерирует эти файлы для вас, также вы можете указать, что несколько языков / идей игнорируют файлы, объединенные в один документ.
Вот отрывок из .gitignore недавнего проекта, над которым я работал. Я извлек те, которые, как мне кажется, связаны с Visual Studio, включая результаты компиляции; это кроссплатформенный проект, поэтому существуют различные другие правила игнорирования файлов, созданных другими системами сборки, и я не могу гарантировать, что я их точно разделил.
Возможно, этот вопрос должен быть вики Сообщества, чтобы мы все вместе могли редактировать один главный список с комментариями о том, какие файлы следует игнорировать для каких типов проектов?
См. Комментарий Джеймса Грегори к другому ответу: «Я был бы осторожен, игнорируя .exe и .pdb, вы можете случайно проигнорировать инструменты, которые храните вместе с вашим источником (nant, nunit gui и т. Д.)» - Джеймс Грегори 21 мая 2010 г. в 13:32 "
@JimRaden В общем, лучше избегать проверки бинарных инструментов в Git. Лучше всего проверять исходный код только в Git; если вам нужны бинарные инструменты, включите скрипт для их установки или подмодуль только с этими инструментами.
Благодарим Йенса Леманна за это - если вы держите исходные каталоги отдельно от файлов проекта компилятора и вывода сборки, вы можете упростить свой .gitignore, отрицая его:
Вы не говорите, какой язык (и) вы используете, но вышеперечисленное должно работать для проектов C ++.
Поздно на вечеринку здесь, но я также обнаружил, что использую следующее. Некоторые из них могут быть полезны только для скрытия конфиденциальных файлов при отправке на общедоступный пульт.
Если вы используете в своем решении dbproj, вам нужно добавить следующее:
Вы можете создать или отредактировать файл .gitignore для своего репо, перейдя в представление «Параметры» в Team Explorer и выбрав «Параметры репозитория». Выберите Edit для вашего .gitignore.
Он автоматически создает фильтры, которые игнорируют все каталоги сборки VS и т. Д.
Больше информации смотрите здесь .
В Visual Studio есть ярлык , потому что он поддерживает Git из коробки в 2015 году или более поздней версии. Для новых решений (или некоторых, у которых нет .git папки) используйте функции управления версиями в обозревателе решений :
Щелкните правой кнопкой мыши свое решение и выберите Add Solution to Source Control. элемент во всплывающем меню.
Он автоматически инициализирует .git репозиторий, добавляет .gitignore необходимые вещи в ваше решение и даже .gitattributes файл (окончания строк и т. Д.).
Текст появится в консоли VS:
Откройте Visual Studio и решение, для которого требуется файл игнорирования. В верхнем меню выберите Git> Настройки.
Приведенное выше откроет параметры Visual Studio с выбранным Source Control> Git Global Settings. В списке слева выберите Git Repository Settings, а затем нажмите кнопку « Добавить» для игнорирования файла .
Приведенное выше добавит файл .gitignore, в котором все нужные файлы будут проигнорированы для типичной установки Visual Studio.
Это в значительной степени подход MS, который использует встроенный тестер Visual Studio, а также проект, который может иметь некоторые привязки TFS.
Как упоминалось на другом плакате, Visual Studio генерирует это как часть своего .gitignore (по крайней мере, для MVC 4):
Поскольку ваш проект может быть подпапкой вашего решения, а файл .gitignore хранится в корне решения, это фактически не коснется файлов локальной базы данных (Git видит их в projectfolder/App_Data/*.mdf ). Чтобы учесть это, я изменил эти строки следующим образом:
Фактически, git также сопоставляет шаблоны относительно подкаталогов, если вы не начинаете их с " / ", и в этом случае они сопоставляют только вещи в том же каталоге, что и .gitignore файл.
Это должно зависеть от проекта или языка, который вы используете. Таким образом, должны быть включены расширения, связанные со сборкой, папкой, файлом sln, папкой bin и т. Д. Для получения полного списка файлов игнорирования git вы можете проверить это репозиторий gitignore для Visual Studio.
Некоторые проекты могут захотеть добавить *.manifest их в свой файл Visual Studio gitignore.io .
Это связано с тем, что некоторые свойства новых проектов Visual Studio настроены на создание файла манифеста.
Но если вы сгенерировали их, и они статичны (не меняются с течением времени), то рекомендуется удалить их из .gitignore файла.
Это то, что только что сделал такой проект, как Git для Windows (для Git 2.24, Q4 2019).
.gitignore : stop ignoring .manifest files
On Windows, it is possible to embed additional metadata into an executable by linking in a "manifest", i.e. an XML document that describes capabilities and requirements (such as minimum or maximum Windows version).
These XML documents are expected to be stored in .manifest files.
At least some Visual Studio versions auto-generate .manifest files when none is specified explicitly, therefore we used to ask Git to ignore them.
However, we do have a beautiful .manifest file now: compat/win32/git.manifest , so neither does Visual Studio auto-generate a manifest for us, nor do we want Git to ignore the .manifest files anymore.
Not every file in your project should be tracked by Git. Temporary files from your development environment, test outputs, and logs, are all examples of files that probably don't need to be tracked. You can use different mechanisms to let Git know which files in your project shouldn't be tracked, and to ensure Git won't report changes to those files. For files that aren't tracked by Git, you can use a .gitignore or exclude file. For files that are tracked by Git, you can tell Git to stop tracking them and to ignore changes.
In this article you learn how to:
- Ignore changes to untracked files by using a .gitignore file
- Ignore changes to untracked files by using an exclude file
- Stop tracking a file and ignore changes using git update-index
- Stop tracking a file and ignore changes using git rm
Use a gitignore file
You can tell Git not to track certain files in your project by adding and configuring a .gitignore file. Entries in a .gitignore file only apply to untracked files, and won't prevent Git from reporting changes to tracked files. Tracked files are files that were committed and exist in the last Git snapshot.
Each line in a .gitignore file specifies a file search pattern relative to the .gitignore file path. The .gitignore syntax is flexible and supports the use of wildcards to specify individual or multiple files by name, extension, and path. Git matches .gitignore search patterns to the files in your project to determine which files to ignore.
Typically, you'll just add a .gitignore file to the root folder of your project. However, you can add a .gitignore file to any project folder to let Git know which files to ignore within that folder and its subfolders at any nested depth. For multiple .gitignore files, the file search patterns specified by a .gitignore file within a folder take precedence over the patterns specified by a .gitignore file within a parent folder.
You can manually create a .gitignore file and add file pattern entries to it, or save time by downloading a .gitignore template for your development environment from the GitHub gitignore repo. One of the benefits of using a .gitignore file is that you can commit changes and share it with others.
Visual Studio 2019 version 16.8 and later versions provides a Git version control experience while maintaining the Team Explorer Git user interface. To use Team Explorer, uncheck Tools > Options > Preview Features > New Git user experience from the menu bar. You can use Git features from either interface interchangeably. Below, we provide a side-by-side comparison of how to create and add entries to a .gitignore file.
Visual Studio automatically creates a .gitignore file for the Visual Studio development environment when you create a new Git repo.
Visual Studio Git
In the Git Changes window, right-click any changed file that you want Git to ignore and choose Ignore this local item or Ignore this extension. Those menu options don't exist for tracked files.
Visual Studio Team Explorer
In the Changes view of Team Explorer, right-click any changed file that you want Git to ignore and choose Ignore this local item or Ignore this extension. Those menu options don't exist for tracked files.
The Ignore this local item option adds a new entry to the .gitignore file, and removes the selected file from the list of changed files.
The Ignore this extension option adds a new entry to the .gitignore file, and removes all files with the same extension as the selected file from the list of changed files.
Either option creates a .gitignore file if it doesn't already exist in the root folder of your repo, and adds an entry to it.
Visual Studio automatically creates a .gitignore file in your repo when you create a new repo for your project.
You can edit your .gitignore file for your repo by going to the Settings view in Team Explorer, then selecting Repository Settings. Select Edit for your .gitignore .
Edit a gitignore file
Here are some examples of common file search patterns:
As soon as you modify a .gitignore file, Git updates the list of files that it ignores.
Windows users must use a forward slash path separator in a .gitignore file instead of a backslash. All users must add a trailing / when specifying a folder.
Use a global gitignore file
You can designate a .gitignore file as a global ignore file that applies to all local Git repos. To do so, use the git config command as follows:
A global .gitignore file helps ensure that Git doesn't commits certain file types, such as compiled binaries, in any local repo. File search patterns in a repo-specific .gitignore file have precedence over patterns in a global .gitignore file.
Use an exclude file
You can also add file search pattern entries to the exclude file in the .git/info/ folder of your local repo. The exclude file lets Git know which untracked files to ignore and uses the same file search pattern syntax as a .gitignore file.
Entries in an exclude file only apply to untracked files, and won't prevent Git from reporting changes to committed files that it already tracks. Only one exclude file exists per repo.
Since Git doesn't commit or push the exclude file, you can safely use it to ignore files on your local system without affecting anyone else.
Use Git update-index to ignore changes
Sometimes it's convenient to temporarily stop tracking a local repo file and have Git ignore changes to the file. For example, you might want to customize a settings file for your development environment without the risk of committing your changes. To do so, you can run the git update-index command with the skip-worktree flag:
To resume tracking, run the git update-index command with the --no-skip-worktree flag.
Or, you can temporarily stop tracking a file and have Git ignore changes to the file by using the git update-index command with the assume-unchanged flag. This option is less effective than the skip-worktree flag, because the assume-unchanged flag can be reverted by a Git pull operation that changes file content.
To resume tracking, run the git update-index command with the --no-assume-unchanged flag.
Use Git rm to ignore changes
Entries in a .gitignore or exclude file have no effect on files that Git already tracks. Git tracks files that you've previously committed. To permanently remove a file from the Git snapshot so that Git no longer tracks it, but without deleting it from the filesystem, run the following commands:
Then, use a .gitignore or exclude file entry to prevent Git from reporting changes to the file.
Не все файлы, созданные или обновленные в коде, следует фиксировать в Git. Временные файлы из среды разработки, тестовые выходные данные и журналы — все это примеры файлов, которые создаются, но не являются частью базы кода. Настройте файлы, отслеживаемые Git с помощью функции gitignore .
Из этого руководства вы узнаете, как выполнить следующие задачи:
- Использование gitignore для предотвращения отслеживания файлов
- Игнорировать файлы только в системе
- Игнорировать файлы во всех репозиториях в системе
- Игнорировать изменения в зафиксированных файлах
Использование gitignore для предотвращения отслеживания файлов
Создайте gitignore-файл в репозитории Git, чтобы предотвратить промежуточное хранение нежелательных файлов в Git. Общий доступ к .gitignore в ветви по умолчанию в репозитории. Вы и ваша команда можете обновить файл, чтобы изменить типы файлов, которые следует игнорировать.
Создание .gitignore
Visual Studio 2019 версии 16.8 и более поздних версий предоставляют новое меню Git для управления рабочим процессом Git с меньшим переключением контекста, чем Team Explorer. Процедуры, описанные в этой статье на вкладке Visual Studio 2019, содержат сведения об использовании интерфейса Git, а также Team Explorer. Дополнительные сведения см. в параллельном сравнении Git и Team Explorer.
Visual Studio автоматически создает gitignore-файл в репозитории при создании нового репозитория для проекта.
Скачайте файл template.gitignore для типа проекта и настройте его в соответствии с вашими потребностями. Если проект не соответствует шаблону, можно создать пустой gitignore из командной строки. Перейдите в репозиторий Git и выполните одну из следующих команд, используя сведения о репозитории:
Windows
Linux и macOS
Git применяет .gitignore к папке и любым дочерним папкам, в которых она находится. Рекомендуется поместить gitignore в корневую папку репозитория, чтобы избежать путаницы.
Настройка .gitignore
Измените gitignore , чтобы включить типы файлов, пути и шаблоны файлов в репозитории. Git начинает игнорировать эти файлы сразу после обновления .gitignore. Если другим пользователям в вашей команде нужен тот же набор игнорируемых файлов, обязательно зафиксируйте изменения.
Visual Studio 2019 версии 16.8 и более поздних версий предоставляют новое меню Git для управления рабочим процессом Git с меньшим переключением контекста, чем Team Explorer. Процедуры, описанные в этой статье на вкладке Visual Studio 2019, содержат сведения об использовании интерфейса Git, а также Team Explorer. Дополнительные сведения см. в параллельном сравнении Git и Team Explorer.
Вы можете изменить gitignore-файл для репозитория, перейдя в представление Параметры в Team Explorer, а затем выбрав репозиторий Параметры. Выберите "Изменить " для .gitignore.
Используйте текстовый редактор, например следующий пример, в который используется Vim:
Каждая строка в .gitignore исключает файл или набор файлов, соответствующих шаблону. Полный синтаксис gitignore очень гибкий. Ниже приведены некоторые примеры наиболее распространенных записей:
Windows пользователей: все пути к файлам в файле Gitignore используют разделитель косой черты, а не обратную косую черту.
Игнорировать файлы только в системе
Gitignore предоставляется всем участникам команды в виде файла, зафиксированного и отправленного в репозиторий Git. Чтобы исключить файлы только в системе, измените файл GIT/info/exclude в локальном репозитории. Изменения в этом файле не передаются другим пользователям. Они применяются только к файлам в этом репозитории. Синтаксис этого файла аналогичен синтаксису, используемому в .gitignore.
Игнорировать файлы во всех репозиториях в системе
Настройте глобальный gitignore для использования во всех репозиториях в системе с помощью программы командной строки git config , как показано в следующем примере:
Этот подход полезен для игнорирования целых типов файлов, которые вы не хотите зафиксировать, например скомпилированные двоичные файлы.
Игнорировать изменения в зафиксированных файлах
Временно игнорировать изменения
Во время разработки удобно прекратить отслеживание изменений в файле, зафиксированном в репозитории Git. Этот подход полезен при настройке параметров или файлов конфигурации, которые являются частью источника проекта для собственной рабочей среды.
Возобновление отслеживания файлов с помощью следующей команды:
Вместо этого можно использовать следующие параметры. Эти параметры в основном предназначены для маркировки файлов, которые не должны изменяться разработчиками.
Чтобы отключить отслеживание изменений, выполните приведенные действия.
Чтобы возобновить отслеживание изменений, выполните приведенные действия.
Постоянное прекращение отслеживания файла
Если файл уже отслеживается Git, .gitignore не применяется. Git продолжит отслеживать изменения в этом файле.
Если вы хотите прекратить отслеживание файла, необходимо явно сообщить Git, что он удален из отслеживания. Следуя этим указаниям, файл останется в локальном рабочем каталоге, но больше не будет отслеживаться в Git.
Добавьте файл в папку .gitignore .
Выполните следующую команду:
Зафиксируйте удаление файла и обновленный gitignore в репозитории.
Not every file in your project should be tracked by Git. Temporary files from your development environment, test outputs, and logs, are all examples of files that probably don't need to be tracked. You can use different mechanisms to let Git know which files in your project shouldn't be tracked, and to ensure Git won't report changes to those files. For files that aren't tracked by Git, you can use a .gitignore or exclude file. For files that are tracked by Git, you can tell Git to stop tracking them and to ignore changes.
In this article you learn how to:
- Ignore changes to untracked files by using a .gitignore file
- Ignore changes to untracked files by using an exclude file
- Stop tracking a file and ignore changes using git update-index
- Stop tracking a file and ignore changes using git rm
Use a gitignore file
You can tell Git not to track certain files in your project by adding and configuring a .gitignore file. Entries in a .gitignore file only apply to untracked files, and won't prevent Git from reporting changes to tracked files. Tracked files are files that were committed and exist in the last Git snapshot.
Each line in a .gitignore file specifies a file search pattern relative to the .gitignore file path. The .gitignore syntax is flexible and supports the use of wildcards to specify individual or multiple files by name, extension, and path. Git matches .gitignore search patterns to the files in your project to determine which files to ignore.
Typically, you'll just add a .gitignore file to the root folder of your project. However, you can add a .gitignore file to any project folder to let Git know which files to ignore within that folder and its subfolders at any nested depth. For multiple .gitignore files, the file search patterns specified by a .gitignore file within a folder take precedence over the patterns specified by a .gitignore file within a parent folder.
You can manually create a .gitignore file and add file pattern entries to it, or save time by downloading a .gitignore template for your development environment from the GitHub gitignore repo. One of the benefits of using a .gitignore file is that you can commit changes and share it with others.
Visual Studio 2019 version 16.8 and later versions provides a Git version control experience while maintaining the Team Explorer Git user interface. To use Team Explorer, uncheck Tools > Options > Preview Features > New Git user experience from the menu bar. You can use Git features from either interface interchangeably. Below, we provide a side-by-side comparison of how to create and add entries to a .gitignore file.
Visual Studio automatically creates a .gitignore file for the Visual Studio development environment when you create a new Git repo.
Visual Studio Git
In the Git Changes window, right-click any changed file that you want Git to ignore and choose Ignore this local item or Ignore this extension. Those menu options don't exist for tracked files.
Visual Studio Team Explorer
In the Changes view of Team Explorer, right-click any changed file that you want Git to ignore and choose Ignore this local item or Ignore this extension. Those menu options don't exist for tracked files.
The Ignore this local item option adds a new entry to the .gitignore file, and removes the selected file from the list of changed files.
The Ignore this extension option adds a new entry to the .gitignore file, and removes all files with the same extension as the selected file from the list of changed files.
Either option creates a .gitignore file if it doesn't already exist in the root folder of your repo, and adds an entry to it.
Visual Studio automatically creates a .gitignore file in your repo when you create a new repo for your project.
You can edit your .gitignore file for your repo by going to the Settings view in Team Explorer, then selecting Repository Settings. Select Edit for your .gitignore .
Edit a gitignore file
Here are some examples of common file search patterns:
As soon as you modify a .gitignore file, Git updates the list of files that it ignores.
Windows users must use a forward slash path separator in a .gitignore file instead of a backslash. All users must add a trailing / when specifying a folder.
Use a global gitignore file
You can designate a .gitignore file as a global ignore file that applies to all local Git repos. To do so, use the git config command as follows:
A global .gitignore file helps ensure that Git doesn't commits certain file types, such as compiled binaries, in any local repo. File search patterns in a repo-specific .gitignore file have precedence over patterns in a global .gitignore file.
Use an exclude file
You can also add file search pattern entries to the exclude file in the .git/info/ folder of your local repo. The exclude file lets Git know which untracked files to ignore and uses the same file search pattern syntax as a .gitignore file.
Entries in an exclude file only apply to untracked files, and won't prevent Git from reporting changes to committed files that it already tracks. Only one exclude file exists per repo.
Since Git doesn't commit or push the exclude file, you can safely use it to ignore files on your local system without affecting anyone else.
Use Git update-index to ignore changes
Sometimes it's convenient to temporarily stop tracking a local repo file and have Git ignore changes to the file. For example, you might want to customize a settings file for your development environment without the risk of committing your changes. To do so, you can run the git update-index command with the skip-worktree flag:
To resume tracking, run the git update-index command with the --no-skip-worktree flag.
Or, you can temporarily stop tracking a file and have Git ignore changes to the file by using the git update-index command with the assume-unchanged flag. This option is less effective than the skip-worktree flag, because the assume-unchanged flag can be reverted by a Git pull operation that changes file content.
To resume tracking, run the git update-index command with the --no-assume-unchanged flag.
Use Git rm to ignore changes
Entries in a .gitignore or exclude file have no effect on files that Git already tracks. Git tracks files that you've previously committed. To permanently remove a file from the Git snapshot so that Git no longer tracks it, but without deleting it from the filesystem, run the following commands:
Then, use a .gitignore or exclude file entry to prevent Git from reporting changes to the file.
Which files should I include in .gitignore when using Git in conjunction with Visual Studio Solutions ( .sln ) and Projects?
I would be careful ignoring .exe and .pdb's, you may inadvertently ignore tooling that you store with your source (nant, nunit gui, etc. ).
22 Answers 22
Please note. This file contains an entry to ignore published files. However the way the rule is written, it will ignore Any folder you have called "Publish", and will there fore ignore anything you have under neath it. It does not specifically target the Visual Studio "Publishing" output. It will ignore it, but also other things.
@starfighterxyz if you think there is a bug in the gitignore, I would recommend creating a pull request.
Well, I dont know (enough?) to say its a bug. I just happend to be using Publish/ as a Controller name, and as Project Folder names. I think this is just an edge case. Just something to save a few hours of your life :)
Any idea why Windows specific files like Thumbs.db and Desktop.ini are not listed in the file from the mentioned link?
On 8/20/2014, here's the file that is generated for Visual Studio + Windows.
Ideally, it would include a license inside the file. (Ideally, that would be a license that raises no questions in a corporate environment.)
@PerLundberg One reason worth considering is you can configure standard project formatting options, etc, and save the config files with the project. If this is in git, it makes it easier for everyone using Resharper to keep the project formatted consistently.
For those interested in what Microsoft thinks should be included in the gitignore, here's the default one which Visual Studio 2013 RTM automatically generates when creating a new Git-Repository:
While you should keep your NuGet packages.config file, you should exclude the packages folder:
I typically don't store binaries, or anything generated from my source, in source control. There are differing opinions on this however. If it makes things easier for your build system, do it! I would however, argue that you are not versioning these dependencies, so they will just take up space in your repository. Storing the binaries in a central location, then relying on the packages.config file to indicate which version is needed is a better solution, in my opinion.
anyone care to elaborate on why you'd want to exclude the packages folder? doesn't it make sense to include the packages for the build server to have the dependencies?
It's worth noting that the NuGet team implemented the 'package restore' feature for exactly this problem. There's a document on the NuGet site which explains the feature and describes how to use it in Visual Studio.
If you ignore packages and are using nuget package restore, it's helpful to allow nuget.exe. When someone downloads, this tells helps VS tell that the feature has been enabled for the solution: !NuGet.exe
For those of you using AppHarbor, it's worth noting that excluding the packages folder will cause your build to fail deployment :)
I understand this is an old question, still sharing an information. In Visual Studio 2017, you can just right click on the solution file and select Add solution to source control
This will add two files to your source folder.
This is the easiest way.
How do you view those files in Visual Studio? they are created in the solution folder but not visible in the solution explorer
I prefer to exclude things on an as-needed basis. You don't want to shotgun exclude everything with the string "bin" or "obj" in the name. At least be sure to follow those with a slash.
Here's what I start with on a VS2010 project:
And only because I use ReSharper, also this:
Agree. Also, this goes for "debug". Add the trailing slash to this to avoid ignoring files with debug in the name.
In Visual Studio 2015 Team Explorer > Local Git Repositories > Project > Settings > Git > Repository Settings > Ignore & Attribute Files.You can add .gitignore file with items should be ignored in visual studio solutions by default.
On Visual Studio 2015 Update 3, and with Git extension updated as of today (2016-10-24), the .gitignore generated by Visual Studio is:
Open Visual Studio and the solution needing an ignore file. From the top menu select Git > Settings.
The above will open Visual Studio’s Options with Source Control > Git Global Settings selected. From the list on the left select Git Repository Settings and then click the Add button for Ignore file.
The above will add a .gitignore file with all the proper files ignored for a typical Visual Studio setup.
Added InstallShield ignores for the build deployment. InstallShield is the new direction Microsoft is headed over Visual Studio Installer, so we've started using it on all new projects. This added line removes the SingleImage installation files. Other InstallShield types may include DVD distribution among others. You may want to add those directory names or just [Ee]xpress/ to prevent any InstallShield LE deployment files from getting into the repo.
Just a clarification - it's actually moving BACK to InstallShield, which existed previous to VisualStudio installer, at least as far back as 1998!
I know this is an old thread but for the new and the old who visit this page, there is a website called gitignore.io which can generate these files. Search "visualstudio" upon landing on the website and it will generate these files for you, also you can have multiple languages/ides ignore files concatenated into the one document.
Here's an extract from a .gitignore on a recent project I was working on. I've extracted the ones that I believe are related to Visual Studio, including the compilation outputs; it's a cross platform project, so there are various other ignore rules for files produced by other build systems, and I can't guarantee that I separated them out exactly.
Perhaps this question should be Community Wiki, so we can all edit together one master list with comments about which files should be ignored for which types of project?
See James Gregory's comment on another answer: "I would be careful ignoring .exe and .pdb's, you may inadvertently ignore tooling that you store with your source (nant, nunit gui, etc. ). – James Gregory May 21 '10 at 13:32"
@JimRaden In general, it's best to avoid checking in binary tools into Git. Best practices are to only check in your source to Git; if you need binary tools, include a script for installing them or a submodule with just those tools.
Credit to Jens Lehmann for this one - if you keep source directories separate to your compiler project files and build output, you could simplify your .gitignore by negating it:
You don't say what language(s) you're using, but the above should work for C++ projects.
Late to the party here, but I also find that I use the following. Some may only be useful for hiding sensitive files when pushing to a public remote.
You can create or edit your .gitignore file for your repo by going to the Settings view in Team Explorer, then selecting Repository Settings. Select Edit for your .gitignore.
It automatically creates filters that will ignore all the VS specific build directories etc.
More info have a look here.
If you are using a dbproj in your solution you will want to add the following:
There is a shortcut in Visual Studio, because it supports Git out of the box in 2015 or above. For new solutions (or some which don't have .git folder) use source control features in Solution Explorer:
Right-click on your solution and select Add Solution to Source Control. item in the popup menu.
It automatically initializes .git repository, adds .gitignore with necessary things to your solution and even .gitattributes file (line endings, etc.).
The text will appeared in the VS console:
This is pretty much an all MS approach, that uses the built in Visual Studio tester, and a project that may have some TFS bindings in there too.
As mentioned by another poster, Visual Studio generates this as a part of its .gitignore (at least for MVC 4):
Since your project may be a subfolder of your solution, and the .gitignore file is stored in the solution root, this actually won't touch the local database files (Git sees them at projectfolder/App_Data/*.mdf ). To account for this, I changed those lines like so:
Actually, git matches patterns relative to subdirectories, too, unless you start them with " / ", in which case they only match things in the same directory as the .gitignore file.
It should depend on the project or language you are using. So extensions related to build, vs folder , sln file , bin folder etc are to be included. For full list of git ignore files you can check this repo gitignore for visual studio
Some project might want to add *.manifest to their visual studio gitignore.io file.
That is because some Visual Studio project properties of new projects are set to generate a manifest file.
But if you have generated them and they are static (not changing over time), then it is a good idea to remove them from the .gitignore file.
That is what a project like Git for Windows just did (for Git 2.24, Q4 2019)
.gitignore : stop ignoring .manifest files
On Windows, it is possible to embed additional metadata into an executable by linking in a "manifest", i.e. an XML document that describes capabilities and requirements (such as minimum or maximum Windows version).
These XML documents are expected to be stored in .manifest files.
At least some Visual Studio versions auto-generate .manifest files when none is specified explicitly, therefore we used to ask Git to ignore them.
However, we do have a beautiful .manifest file now: compat/win32/git.manifest , so neither does Visual Studio auto-generate a manifest for us, nor do we want Git to ignore the .manifest files anymore.
Читайте также: