(转)WP7 断点续传
原文地址:http://www.cnblogs.com/bryht/archive/2012/03/26/2418299.html
断点续传其实就是在请求流的时候请求中间流,而不是每次重新从头来过
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.CreateHttp(URL);
Myrq.Headers["Range"] = "bytes=1024-";//设置Range值
这句就是请求1024位置开始到末尾的流
如果Myrq.Headers["Range"] = "bytes=1024-2048";
则表示请求1024到2048位置的数据
有了这个方法,写断点续传就会简单许多了,错略的方法如下
public void DownFile(string URL, string Filename, ProgressBar Prog)
{
//打开上次下载的文件或新建文件
long lStartPos = 0;
IsolatedStorageFileStream fs;
if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(Filename))
{
fs = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(Filename, FileMode.Open);
lStartPos = fs.Length;
fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
}
else
{
fs = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(Filename);
lStartPos = 0;
}
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.CreateHttp(URL);
Myrq.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)";
if (lStartPos > 0)
{
Myrq.Headers["Range"] = "bytes=" + lStartPos + "-";//设置Range值
}
Myrq.BeginGetResponse(new AsyncCallback((a) =>
{
var myrp = Myrq.EndGetResponse(a);
long totalBytes = myrp.ContentLength + fs.Length;
this.Dispatcher.BeginInvoke(() => { Prog.Maximum = (int)totalBytes; });
Stream st = myrp.GetResponseStream();
//Stream so = new FileStream(Filename, FileMode.Create);
long totalDownloadedByte = fs.Length;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
fs.Write(by, 0, osize);
this.Dispatcher.BeginInvoke(() => { Prog.Value = (int)totalDownloadedByte; });
osize = st.Read(by, 0, (int)by.Length);
}
fs.Close();
st.Close();
MessageBox.Show("下载完毕!");
}), null);
}
catch (Exception ex)
{
MessageBox.Show("提示" + ex.Message);
}
}
http://blog.bryht.net
http://blog.bryht.net