You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自定义NuGet包安装/卸载时执行对应操作?

解决NuGet包卸载时删除.editorconfig的方案

针对现代NuGet(.NET Core/.NET 5+),由于install.ps1/uninstall.ps1已被弃用,可采用以下两种可行方案:

方案1:优化MSBuild部署+手动/自动清理目标

步骤1:修改安装逻辑(仅首次部署)

更新NuGet包的props文件,仅当项目根目录不存在.editorconfig时才复制文件,避免每次构建重复执行:

<ItemGroup>
  <EditorConfigFilesToCopy Include="$(MSBuildThisFileDirectory)../content/.editorconfig" />
</ItemGroup>

<Target Name="DeployEditorConfig" BeforeTargets="BeforeBuild" Condition="!Exists('$(MSBuildProjectDirectory)/.editorconfig')">
  <Message Text="Deploying .editorconfig from [你的NuGet包名]" />
  <Copy
    SourceFiles="@(EditorConfigFilesToCopy)"
    DestinationFolder="$(MSBuildProjectDirectory)"
    SkipUnchangedFiles="true" />
</Target>

步骤2:添加清理目标

在NuGet包的targets文件中添加清理目标,支持手动触发或结合dotnet clean自动执行:

<Target Name="CleanupEditorConfig" AfterTargets="Clean">
  <Message Text="Removing .editorconfig deployed by [你的NuGet包名]" />
  <Delete Files="$(MSBuildProjectDirectory)/.editorconfig" Condition="Exists('$(MSBuildProjectDirectory)/.editorconfig')" />
</Target>
  • 用户卸载NuGet包后,只需执行dotnet msbuild /t:CleanupEditorConfig即可删除文件;
  • 若用户执行dotnet clean,也会自动触发该清理逻辑。

方案2:将.editorconfig作为项目内容项部署

这种方式利用NuGet的content/contentFiles特性,将文件添加到项目中,卸载时NuGet会自动移除项目引用,用户可选择删除物理文件:

步骤1:配置NuGet包文件结构

将.editorconfig放在NuGet包的content目录下,或现代推荐的contentFiles/any/any目录下。

步骤2:更新nuspec配置

<files>
  <!-- 传统content方式,兼容旧版NuGet -->
  <file src="content/.editorconfig" target="content" />
  <!-- 现代contentFiles方式,推荐用于.NET Core+项目 -->
  <file src="contentFiles/any/any/.editorconfig" target="contentFiles/any/any" />
</files>

<contentFiles>
  <files include="any/any/.editorconfig" buildAction="None" copyToOutput="false" flatten="true" />
</contentFiles>
  • 安装包时,.editorconfig会被复制到项目根目录并添加到项目文件中;
  • 卸载包时,NuGet会自动从项目文件中移除该文件的引用,若文件未被修改,用户可直接删除物理文件。

针对.NET Framework项目的兼容方案

若你的NuGet包需要支持.NET Framework项目,可继续使用已弃用但仍生效的uninstall.ps1脚本:
在NuGet包的tools目录下创建uninstall.ps1:

param($installPath, $toolsPath, $package, $project)

$editorConfigPath = Join-Path $project.FullName ".editorconfig"
if (Test-Path $editorConfigPath) {
  Remove-Item $editorConfigPath -Force
  Write-Host "Removed .editorconfig deployed by $($package.Id)"
}

内容的提问来源于stack exchange,提问作者Shay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:44:56