including-generated-files
Что он делает
Этот скилл исправляет шаги сборки, которые создают файлы, но эти файлы не компилируются и не копируются, потому что MSBuild составляет списки файлов до запуска сборки. Он нужен разработчикам, у которых код или контент, созданный сборкой, теряется.
Когда использовать
- ✓Когда шаг сборки создаёт исходный файл, который не компилируется.
- ✓Когда созданный файл отсутствует в папке вывода.
- ✓Когда файл, созданный во время сборки, не попадает в проект.
Ссылка на скилл
https://github.com/dotnet/skills/blob/main/plugins/dotnet-msbuild/skills/including-generated-files/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Моя сборка создаёт файл на C# во время работы, но компилятор его не видит. Исправь цель, чтобы он попал в сборку.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент добавляет созданный файл в списки компиляции и отслеживаемых выходных файлов внутри цели, которая его создаёт, и настраивает запуск этой цели до компиляции.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Including Generated Files Into Your Build
Overview
Files generated during the build are generally ignored by the build process. This leads to confusing results such as:
- Generated files not being included in the output directory
- Generated source files not being compiled
- Globs not capturing files created during the build
This happens because of how MSBuild's build phases work.
Quick Takeaway
For code files generated during the build - we need to add those to Compile and FileWrites item groups within the target generating the file(s):
<ItemGroup>
<Compile Include="$(GeneratedFilePath)" />
<FileWrites Include="$(GeneratedFilePath)" />
</ItemGroup>
The target generating the file(s) should be hooked before CoreCompile and BeforeCompile targets - BeforeTargets="CoreCompile;BeforeCompile"
Why Generated Files Are Ignored
For detailed explanation, see How MSBuild Builds Projects.
Evaluation Phase
MSBuild reads your project, imports everything, creates Properties, expands globs for Items outside of Targets, and sets up the build process.
Execution Phase
MSBuild runs Targets & Tasks with the provided Properties & Items to perform the build.
Key Takeaway: Files generated during execution don't exist during evaluation, therefore they aren't found. This particularly affects files that are globbed by default, such as source files (.cs).
Solution: Manually Add Generated Files
When files are generated during the build, manually add them into the build process. The approach depends on the type of file being generated.
Use $(IntermediateOutputPath) for Generated File Location
Always use $(IntermediateOutputPath) as the base directory for generated files. Do not hardcode obj\ or construct the intermediary path manually (e.g., obj\$(Configuration)\$(TargetFramework)\). The intermediate output path can be redirected to a different location in some build configurations (e.g., shared output directories, CI environments). Using $(IntermediateOutputPath) ensures your target works correctly regardless of the actual path.
Always Add Generated Files to FileWrites
Every generated file should be added to the FileWrites item group. This ensures that MSBuild's Clean target properly removes your generated files. Without this, generated files will accumulate as stale artifacts across builds.
<ItemGroup>
<FileWrites Include="$(IntermediateOutputPath)my-generated-file.xyz" />
</ItemGroup>
Basic Pattern (Non-Code Files)
For generated files that need to be copied to output (config files, data files, etc.), add them to Content or None items before BeforeBuild:
<Target Name="IncludeGeneratedFiles" BeforeTargets="BeforeBuild">
<!-- Your logic that generates files goes here -->
<ItemGroup>
<None Include="$(IntermediateOutputPath)my-generated-file.xyz" CopyToOutputDirectory="PreserveNewest"/>
<!-- Capture all files of a certain type with a glob -->
<None Include="$(IntermediateOutputPath)generated\*.xyz" CopyToOutputDirectory="PreserveNewest"/>
<!-- Register generated files for proper cleanup -->
<FileWrites Include="$(IntermediateOutputPath)my-generated-file.xyz" />
<FileWrites Include="$(IntermediateOutputPath)generated\*.xyz" />
</ItemGroup>
</Target>
For Generated Source Files (Code That Needs Compilation)
If you're generating .cs files that need to be compiled, use BeforeTargets="CoreCompile;BeforeCompile". This is the correct timing for adding Compile items — it runs late enough that the file generation has occurred, but before the compiler runs. Using BeforeBuild is too early for some scenarios and may not work reliably with all SDK features.
<Target Name="IncludeGeneratedSourceFiles" BeforeTargets="CoreCompile;BeforeCompile">
<PropertyGroup>
<GeneratedCodeDir>$(IntermediateOutputPath)Generated\</GeneratedCodeDir>
<GeneratedFilePath>$(GeneratedCodeDir)MyGeneratedFile.cs</GeneratedFilePath>
</PropertyGroup>
<MakeDir Directories="$(GeneratedCodeDir)" />
<!-- Your logic that generates the .cs file goes here -->
<ItemGroup>
<Compile Include="$(GeneratedFilePath)" />
<FileWrites Include="$(GeneratedFilePath)" />
</ItemGroup>
</Target>
Note: Specifying both CoreCompile and BeforeCompile ensures the target runs before whichever target
Частые вопросы
Почему сгенерированные файлы игнорируются?
MSBuild читает шаблоны файлов на этапе вычисления, до того как цель создаст файл, поэтому нового файла в списке нет.
Где нужно добавить файл?
Его добавляют внутри цели, которая его создаёт, чтобы он попал в список вовремя.
Работает ли это для чистых сборок?
Да. Отслеживание файла помогает командам очистки удалить его.
Подробности
Оригинальное описание автора
Own MSBuild generated-artifact integration. USE FOR: a target that creates or should create source, Content, None, or another physical file but the artifact is missing from compilation or output; target timing; evaluation-time glob misses; $(IntermediateOutputPath) placement; and FileWrites clean tracking. The prompt may describe the generated artifact without naming the producing task. DO NOT USE when the primary defect is general Include/Remove/Update semantics, item metadata or batching, duplicate/overlapping declarations, or a generated-item identity relationship; use item-management. Excl
repo: dotnet/skills
Популярность
- Звёзды на GitHub
- 5.8k
- Место в рейтинге
- #14601
- Лицензия
- MIT
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
create-custom-agent
5.8kПомогает агенту создавать файлы пользовательских агентов для VS Code со своими инструментами, инструкциями и передачей работы другим агентам.
create-skill
5.8kПомогает агенту создать новый скилл с корректным именем, понятным описанием триггера и файлом SKILL.md по стандарту.
csharp-scripts
5.8kПомогает агенту запустить небольшую программу на C# как один файл с помощью командного инструмента .NET, без создания полного проекта.
dotnet-pinvoke
5.8kПомогает агенту правильно вызывать нативные библиотеки C и C++ из .NET: сигнатуры, работу со строками, память и безопасные дескрипторы.
Похожие скиллы
openclaw-update
394kПомогает агенту обновить уже работающий OpenClaw Gateway, выбрав способ обновления по тому, как он был установлен, и сохранив вашу сессию.
diagnose-gateway
394kПомогает агенту выяснить, почему ваш OpenClaw Gateway не работает, проверяя настройки, каналы и порты, но ничего не меняя.
crabbox-apps
394kПомогает агенту открыть и запустить приложение на временной облачной машине, а затем показать его вид на боковой панели чата.