Skip to content

Instantly share code, notes, and snippets.

@ialex32x
Last active March 11, 2022 07:41
Show Gist options
  • Save ialex32x/5458207 to your computer and use it in GitHub Desktop.
Save ialex32x/5458207 to your computer and use it in GitHub Desktop.
C# simple http download sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
//d41d8cd98f0b24e980998ecf8427e
static string B2S(byte[] bs)
{
var sb = new StringBuilder((int)(bs.Length * .5f));
foreach (var c in bs)
{
sb.AppendFormat("{0:x}", c);
}
return sb.ToString();
}
static void Main(string[] args)
{
var buf = new byte[1024 * 512];
var url = new Uri("http://foodatcoa.sinaapp.com/WebPlayer/bundle/data.asset");
var req = (HttpWebRequest)WebRequest.Create(url);// HttpWebRequest.CreateHttp(url);
var md5 = System.Security.Cryptography.MD5.Create();
req.Method = WebRequestMethods.Http.Get;
req.ContentType = "application/octet-stream";
Console.WriteLine("wait for response");
var rsp = req.GetResponse();
if (rsp.ContentLength > 0)
{
var wfs = System.IO.File.Create("download.asset");
var stream = rsp.GetResponseStream();
var total = 0L;
Console.WriteLine("start: {0}", rsp.ContentLength);
while (total < rsp.ContentLength)
{
var step = stream.Read(buf, 0, buf.Length);
if (step > 0)
{
total += step;
wfs.Write(buf, 0, step);
Console.WriteLine("read {0} bytes ({1})", total, 100f * (float)total / rsp.ContentLength);
}
}
Console.WriteLine("completed.");
stream.Close();
stream.Dispose();
var hash = B2S(md5.ComputeHash(wfs));
Console.WriteLine("hash: {0}", hash);
if ("d41d8cd98f0b24e980998ecf8427e" != hash)
{
Console.WriteLine("ERROR");
}
wfs.Close();
wfs.Dispose();
}
else
{
Console.WriteLine("failed. {0} {1}", rsp.ContentType, rsp.ContentLength);
}
rsp.Close();
rsp.Dispose();
Console.WriteLine("end");
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment