C#复制文件到bin目录

3
我可以使用"copy if newer"属性将文件放入bin目录。但问题是,我需要在我的应用程序旁边放置大量的dll文件,这意味着我的项目变得杂乱无章,文件数量也很多。我想把文件放进解决方案的资产文件夹中,在构建时让文件出现在bin目录中。我尝试过使用后构建事件,但即使成功,我仍然会收到Windows错误代码。是否有其他方法让外部dll文件可供我的应用程序使用呢?

有很多替代方法。例如,可以使用“AppDomain.AssemblyResolve”手动加载程序集。 - Patrick Hofman
@PatrickHofman 这个对于被其他外部程序集引用的外部程序集有效吗? - K-Dawg
“external”是什么意思?程序集只是程序集,对吧? - Patrick Hofman
您可以指定程序集的位置。还可以查看探测元素。 - Alexander Petrov
你是使用msbuild/ csproj文件还是使用新的基于JSON的/无构建文件的方法? - rene
显示剩余6条评论
1个回答

2
如果您卸载项目文件,则可以编辑 .csproj 文件。
在末尾附近,您将找到:
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  -->

让我们进行修改。

首先定义Items,AfterBuild任务将要复制哪些文件。注意,您只需要确保这些文件在磁盘上的文件夹(您称之为assets)中存在并且受源代码控制。您不需要在解决方案或项目中包含任何这些文件。

  <ItemGroup>
    <!-- Include relative to this project file, so ..\assets would bring you to the solution folder 
         Take all files in the assets folder and subfolders, except *.txt files
    -->
    <Asset Include="assets\**" Exclude="*.txt">

    </Asset>
    <!-- take all *.txt files -->
    <TextAsset Include="assets\**\*.txt">
      <!-- meta data -->
      <SubPath>TextFiles</SubPath>
    </TextAsset>  
  </ItemGroup>

现在你将拥有两个项目集合,一个称为Asset,另一个称为TextAsset。这些项目可以在构建任务中使用。我们将使用复制任务。我已经在构建脚本中加了注释来解释发生了什么。
 <!-- this does what the name suggests-->
  <Target Name="AfterBuild">
    <!-- log -->
    <Message Importance="high" Text="Start Copying assets"/>
    <!-- copy Asset files to one folder (flattens) -->
    <Copy SourceFiles="@(Asset)" 
          DestinationFolder="$(OutputPath)"   />
    <!-- copy TextAsset files to a subpath, keep folder structure-->
    <Copy SourceFiles="@(TextAsset)" 
          DestinationFiles="@(TextAsset->'$(OutputPath)%(SubPath)\%(RecursiveDir)%(Filename)%(Extension)')" />
    <!-- done logging -->
    <Message Importance="high" Text="Copied assets"/>
  </Target>

请注意,我使用了属性$(OutputPath),这是众所周知的属性之一。类似的列表也适用于项目元数据
更改不会影响Visual Studio的操作。在添加或删除常规项目项和/或项目设置时,您的更改将被保留。由于您将在源代码控制中保留此文件,因此在构建服务器上也将运行相同的目标,执行相同的复制。
我更喜欢从命令行测试这些构建目标,只指定我感兴趣的目标,如下所示:
msbuild Application2.csproj /t:AfterBuild

那样做可以大大缩短往返时间,而不必进行完整的构建。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接