public class DownFileExe
{
public static string PERSIST_EXP = ".cdel";
public static void download(string url, string path)
{
//下载
path = path + PERSIST_EXP;
simpleDownload(url, path);//开始下载
}
/// <summary>
/// 下载网络资源(支持断点续传)
/// </summary>
/// <param name="url"></param>
/// <param name="path"></param>
public static void simpleDownload(string url, string path)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
WebResponse response = null;
FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
long lStartPos = writer.Length; ;//当前文件大小
long currentLength = 0;
long totalLength = 0;//总大小
try
{
if (File.Exists(path))//断点续传
{
response = request.GetResponse();
long sTotal = response.ContentLength;
if (sTotal == lStartPos)
{
close(writer);
File.Move(path, path.Replace(PERSIST_EXP, ""));
print("下载完成!");
return;
}
writer.Seek(lStartPos, SeekOrigin.Begin);//指针跳转
totalLength = response.ContentLength + lStartPos; //总长度
currentLength = lStartPos; //当前长度
}
else
{
response = request.GetResponse();
totalLength = response.ContentLength;
}
Stream reader = response.GetResponseStream();
byte[] buff = new byte[1024];
int c = 0; //实际读取的字节数
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
currentLength += c;
writer.Write(buff, 0, c);
progressBar(currentLength, totalLength);//进度条
writer.Flush();
}
close(writer);
if (currentLength == totalLength)
{
File.Move(path, path.Replace(PERSIST_EXP, ""));
print("下载完成!");
}
if (reader != null)
{
reader.Close();
reader.Dispose();
response.Close();
}
}
catch (Exception ex)
{
close(writer);
if (response != null)
{
response.Close();
response.Dispose();
}
print("抛出异常:" + ex.StackTrace.ToString() + "," + ex.Message.ToString());
}
}
private static void close(FileStream writer)
{
if (writer != null)
{
writer.Close();
writer.Dispose();
}
}
/// <summary>
/// 进度条
/// </summary>
/// <param name="currentLength">当前长度</param>
/// <param name="totalLength">总长度</param>
public static void progressBar(Object currentLength, Object totalLength)
{
double aaa = System.Convert.ToDouble(currentLength);
double bbb = System.Convert.ToDouble(totalLength);
print(currentLength + "/" + totalLength + "__" + (aaa / bbb).ToString("0.00 %"));
}
/// <summary>
/// 系统输出
/// </summary>
/// <param name="obj"></param>
public static void print(Object obj)
{
Console.WriteLine(obj);
}
}