/// <summary>
/// 斷點續傳
/// </summary>
/// <param name="savePath">保存路徑</param>
/// <param name="loadPath">下載路徑</param>
/// <param name="fileName">文件名稱</param>
/// <param name="flag">備份區分,默認備份名,原文件+.back</param>
/// <returns></returns>
public static bool ResumeDownloadFile(string savePath, string loadPath, string fileName = null, bool flag = true)
{
// 自定義文件名爲空的情況
if (string.IsNullOrEmpty(fileName))
{
// 取得下載文件名
fileName = Path.GetFileName(loadPath);
}
savePath = savePath + fileName;
// 判斷保存路徑是否存在,備份原文件
JustFileAndDic(savePath, true);
// 定義臨時下載路徑
string strLocalPathTemp = savePath + PersistExp;
// 文件下載結果.
bool bDownload = true;
//打開上次下載的文件或新建文件
long lStartPos = 0;
FileStream fs;
if (File.Exists(strLocalPathTemp))
{
fs = File.OpenWrite(strLocalPathTemp);
lStartPos = fs.Length;
fs.Seek(lStartPos, SeekOrigin.Current); //移動文件流中的當前指針
}
else
{
fs = new FileStream(strLocalPathTemp, FileMode.Create);
lStartPos = 0;
}
//打開網絡連接
try
{
// 定義驗證證書的回調函數.
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loadPath);
if (lStartPos > 0)
request.AddRange((int)lStartPos); //設置Range值
//向服務器請求,獲得服務器迴應數據流
Stream ns = request.GetResponse().GetResponseStream();
byte[] nbytes = new byte[512];
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, 512);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, 512);
}
fs.Close();
ns.Close();
// 將文件複製到指定文件夾
File.Copy(strLocalPathTemp, savePath);
// 刪除臨時文件
File.Delete(strLocalPathTemp);
}
catch (Exception e)
{
fs.Close();
// 設定下載結果爲false.
bDownload = false;
}
// 返回下載結果.
return bDownload;
}
下載-斷點續傳
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.