Last active
November 8, 2019 07:43
-
-
Save Serivy/b2653ed2e0a01aca4739fdfbfa3dce2e to your computer and use it in GitHub Desktop.
MSBuild web download task which only downloads newer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<UsingTask TaskName="LDownloadFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll"> | |
<ParameterGroup> | |
<Url ParameterType="System.String" Required="true" /> | |
<File ParameterType="System.String" Required="false" /> | |
<OutputFolder ParameterType="System.String" Required="false" /> | |
<OnlyIfNewer ParameterType="System.Boolean" Required="false" /> | |
</ParameterGroup> | |
<Task> | |
<Using Namespace="System.Web"/> | |
<Code Type="Fragment" Language="cs"><![CDATA[ | |
using (var client = new System.Net.WebClient()) | |
{ | |
var targetFile = (OutputFolder != null ? OutputFolder + "/" : "") + (File ?? System.IO.Path.GetFileName(new Uri(Url).LocalPath)); | |
var serverLastModifiedFile = targetFile+".dl"; | |
string serverLastModified = null; | |
if (OnlyIfNewer) { | |
using (client.OpenRead(Url)) { | |
// targetLength = Convert.ToInt64(client.ResponseHeaders["Content-Length"]); | |
serverLastModified = client.ResponseHeaders["Last-Modified"].ToString(); | |
} | |
// var fileCreate = (new System.IO.FileInfo(targetFile)).CreationTimeUtc; | |
string diskLastModified = null; | |
if (System.IO.File.Exists(serverLastModifiedFile)) { | |
diskLastModified = System.IO.File.ReadAllText(serverLastModifiedFile); | |
} | |
if (!string.IsNullOrEmpty(diskLastModified) && diskLastModified == serverLastModified) { | |
Log.LogMessage("Skipping as already latest (Server: " + serverLastModified + ", Disk:" + diskLastModified + ") >" + targetFile); | |
return true; | |
} | |
Log.LogMessage("File exists but is a different (Server: " + serverLastModified + " Disk:" + diskLastModified + ") >" + targetFile); | |
} | |
client.DownloadFile(Url, targetFile); | |
if (OnlyIfNewer) { | |
System.IO.File.WriteAllText(serverLastModifiedFile, serverLastModified); | |
} | |
Log.LogMessage("Downloaded " + targetFile); | |
} | |
]]></Code> | |
</Task> | |
</UsingTask> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment