如何使用MSBuild计算文件校验和?
我不想依赖MSBuild扩展。
答案 0 :(得分:0)
一种选择是在项目文件中使用C#代码。 该示例显示了如何在C#代码之间传递参数。
<?xml version="1.0" encoding="utf-8"?>
<Project>
<UsingTask TaskName="GenerateHash" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<InputFile ParameterType="System.String" Required="true" />
<Checksum ParameterType="System.String" Output="true" />
</ParameterGroup>
<Task>
<Using Namespace="System.IO" />
<Using Namespace="System.Security.Cryptography" />
<Code Type="Fragment" Language="cs">
<![CDATA[
using (var md5 = MD5.Create())
{
using (var stream = new FileStream(InputFile, FileMode.Open))
{
byte[] bytes = md5.ComputeHash(stream);
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
Checksum = builder.ToString();
}
}
]]>
</Code>
</Task>
</UsingTask>
<Target Name="GenerateManifestJson" AfterTargets="PostBuild" >
<GenerateHash InputFile="$(FileName)">
<Output
TaskParameter="Checksum"
PropertyName="ArtifactChecksum" />
</GenerateHash>
<ItemGroup>
<ManifestJson Include="{" />
<ManifestJson Include="%20"checksum":"$(ArtifactChecksum)"" />
<ManifestJson Include="}" />
</ItemGroup>
<WriteLinesToFile File="c:\temp\hello.manifest.json" Lines="@(ManifestJson)" Overwrite="true" Encoding="utf-8" />
</Target>
</Project>