在编译时将文件复制到应用程序文件夹中

And*_*ker 83 c# visual-studio

如果我有一些文件要从我的项目复制到.\bin\debug\编译文件夹中,那么我似乎必须把它们放到项目的根目录中.将它们放入子文件夹似乎将它们复制到.\bin\debug\与它们存储在同一结构中的文件夹中.

有什么方法可以避免这种情况吗?

只是要清楚:如果我有一个MyFirstConfigFile.txtMySecondConfigFile.txt一个在ConfigFiles文件夹和我设置其复制到输出复制...,那么他们出现在.\bin\debug\ConfigFiles\文件夹中.我希望它们出现在.\bin\debug\文件夹中.

Jos*_*rke 83

您可以使用post build事件执行此操作.在编译时将文件设置为无操作,然后在宏中将文件复制到所需的目录.

这是一个后期构建宏,我认为通过将名为Configuration的目录中的所有文件复制到根构建文件夹来工作:

copy $(ProjectDir)Configuration\* $(ProjectDir)$(OutDir)
Run Code Online (Sandbox Code Playgroud)

  • 正确和测试(Vs2010)宏是:复制"$(ProjectDir)Firebird\firebird_bin\*""$(ProjectDir)$(OutDir)" (9认同)
  • 我认为使用引号是必要的:`copy"$(ProjectDir)subfolder_name \"*"$(ProjectDir)$(OutDir)"` (3认同)

Jho*_*re- 50

您可以在csproj上使用MSBuild任务.

编辑csproj文件

  <Target Name="AfterBuild">
    <Copy SourceFiles="$(OutputPath)yourfiles" DestinationFolder="$(YourVariable)" ContinueOnError="true" />
  </Target>
Run Code Online (Sandbox Code Playgroud)


Geo*_*org 34

您还可以将文件或链接放入解决方案资源管理器的根目录,然后设置文件属性:

Build action = Content

Copy to Output Directory = Copy if newer (例如)

对于链接,将文件从Windows资源管理器拖到解决方案资源管理器中,按住shift和控制键.

在此输入图像描述

  • 这将保留原始的相对路径,这是OP所不能接受的 (2认同)
  • 请参阅[这篇文章](/sf/ask/1312073521/)以获得可接受的替代方案 (2认同)

Jér*_*VEL 13

我个人更喜欢这种方式。

修改.csproj添加

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\MyFirstConfigFile.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

或者概括地说,如果要复制所有子文件夹和文件,可以执行以下操作:

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\**">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(RecursiveDir)\%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,比构建后的活动更好。谢谢你! (2认同)
  • 此外,目前无法在 IDE 中设置目标路径,因此现在我们必须编辑 XML。 (2认同)