通过Http的方式去下载文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace ConsoleApp1
{
public class DownLoad
{
private static int ByteSize = 1024;
/// <summary>
/// 下载中的后缀,下载完成去掉
/// </summary>
private const string Suffix = ".downloading";
public static event Action<int> ShowDownloadPercent;
/// <summary>
/// Http方式下载文件
/// </summary>
/// <param name="url">http地址</param>
/// <param name="localfile">本地文件</param>
/// <returns></returns>
public static int DownloadFile(string url, string localfile)
{
string savePath = @"C:\Users\wr\Desktop\aaa\"+ localfile;
string path = @"C:\Users\wr\Desktop\aaa\"+ localfile;
System.Net.WebClient wc = new System.Net.WebClient();
wc.Headers["User-Agent"] = "blah";
byte[] bateFile = wc.DownloadData(url);
string downLoadPath = string.Empty;
if (localfile.ToString().ToLower().IndexOf("pdf") == -1)
{
downLoadPath = savePath;
}
else
{
downLoadPath = path;
}
System.IO.FileStream fs = new System.IO.FileStream(downLoadPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
fs.Write(bateFile, 0, bateFile.Length);
fs.Flush();
fs.Close();
return 1;
}
/// <summary>
/// 下载完成
/// </summary>
private static void DownloadFileOk(string localfileReal, string localfileWithSuffix)
{
try
{
//去掉.downloading后缀
FileInfo fi = new FileInfo(localfileWithSuffix);
fi.MoveTo(localfileReal);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
//通知完成
if (ShowDownloadPercent != null)
{
ShowDownloadPercent(100);
}
}
}
// 从文件头得到远程文件的长度
private static long GetHttpLength(string url)
{
long length = 0;
HttpWebRequest req = null;
HttpWebResponse rsp = null;
try
{
req = (HttpWebRequest)HttpWebRequest.Create(url);
rsp = (HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
length = rsp.ContentLength;
}
}
catch (Exception ex)
{
Console.WriteLine("获取远程文件大小失败!exception:\n" + ex.ToString());
}
finally
{
if (rsp != null)
{
rsp.Close();
}
if (req != null)
{
req.Abort();
}
}
return length;
}
}
}