I have a set of files inside a folder. They all have a name which matches the pattern DR__.*. I want to copy them to another folder, but removing the DR__ prefix. How can I do this with MSBuild? I used to do it like this using NAnt:
<mkdir dir="${ClientPath + '\bin\' + ConfigurationName + '\Parameters'}"/>
<foreach item="File" property="Filename" in="CVParameters">
<if test="${string::contains(Filename, Client + '_')}">
<property name="newFilename" value="${ string::substring( Filename, string::last-index-of(Filename, '__') + 2, string::get-length(Filename) - string::last-index-of(Filename, '__') - 2) }"/>
<copy file="${ Filename }" tofile="${ ClientPath + '\bin\' + ConfigurationName + '\Parameters\' + newFilename }" overwrite="true"/>
</if>
</foreach>
I agree with @Si's solution. But with MSBuild 4.0 you can do it with built in functionality. NAnt script is much clearer than mine. But I will add it as a solution just to show MSBuild 4.0 techniques:
Edit (by OP): To get this working, I had to replace
$(DestinationFullPath)
inCopy
with@(DestinationFullPath)
, to match the number of Source and Destination Files. Also, I had to change the prefix toDR__
, sinceDR__.
wouldn't work.I recently had to do something similar to this as well, and ended up with a hacky, but workable solution based on in-line custom tasks.
Can you use MSBuild 4.0? If so, then refer to this answer (and MSDN help). Otherwise the RegexReplace task in MSBuildCommunityTasks should also work, at the cost of having to support an external tool (so go MSBuild 4.0 if possible).
Another (untested) option is the TextString task in MSBuildExtensionPack.
Failing those, roll your own task?
Recently I had to solve similar task and I did it using Item's metadata. Advantages of this solution are:
<TempItemsBak Include="@(TempItems-> ... CustomTransform ... )">
will get original item's metadata values so you can use it for further processing)<Project DefaultTargets="CopyNoPrefix" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">