如何用C#做下载管理,要有暂停,断点保存,退出保存下载进度.....
我有一个项目要做下载管理,我做了一个demo,然后遇到了一些下载管理方面的问题。
1. 但是在做暂停,重启的时候遇到了问题,特别是在我退出软件,然后重启之后如何继续下载。
2. 我得到的Stream不支持seek;(Stream str = client.OpenRead(URLAddress); )要不然我可以记录一下位置,然后Seek过去。
希望大家给点建议,有源码最好了。
private void StartDownload()
{
WebClient client = new WebClient();
Start.BeginInvoke(new changeStaushandler(ChangeStaus));
//Start.Enabled = false;
string URL = srcAddress.Text;
int n = URL.LastIndexOf("/");
int m1 = URL.LastIndexOf("?");
if (m1 < 0)
{
m1 = URL.Length;
}
string URLAddress = URL;
string fileName = URL.Substring(n + 1, m1-n-1);
string Dir = tarAddress.Text;
string Path = Dir + "\\" + fileName+".tmp";
long size = 0;
long ChunkSize = 102400;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)GetRequest(URLAddress).GetResponse();
size = response.ContentLength;
}
catch (WebException exp)
{
MessageBox.Show(exp.Message, "Error");
}
try
{
statusBar.BeginInvoke(new ChangeStausbarhandler(ChanageStausbar), "开始下载文件");
//statusBar.Text = "开始下载文件...";
//client.DownloadFile(URLAddress, fileName);
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
int startmbyte = 0;
statusBar.BeginInvoke(new ChangeStausbarhandler(ChanageStausbar), "正在接收数据");
//statusBar.Text = "正在接收数据...";
FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Close();
while (size > 0)
{
fstr = new FileStream(Path, FileMode.Append, FileAccess.Write);
byte[] mbyte = new byte[ChunkSize];
//long seek = str.Seek(1000000, SeekOrigin.Current);
int lengthRead = str.Read(mbyte, 0,Convert.ToInt32(ChunkSize));
if (lengthRead == 0)
break;
fstr.Write(mbyte, startmbyte, lengthRead);
size -= lengthRead;
fstr.Close();
}
str.Close();
str.Flush();
client.Dispose();
statusBar.BeginInvoke(new ChangeStausbarhandler(ChanageStausbar), "下载完毕!");
//statusBar.Text = "下载完毕!";
}
catch (WebException exp)
{
MessageBox.Show(exp.Message, "Error");
statusBar.BeginInvoke(new ChangeStausbarhandler(ChanageStausbar), "");
//statusBar.Text = "";
}
Start.BeginInvoke(new changeStaushandler(ChangeStaus));
//Start.Enabled = true;
}