我尝试创建一个ftp下载应用程序。而且我想限制我的下载,但我是noob,所以我写了这个,但我无法准确控制速度,我的意思是当我每秒写入1024 * 1024字节时,它每秒下载400到1700 kb,所以我真的需要帮助这个,我告诉我,我只是一个菜鸟所以请告诉答案的新手。谢谢大家,感谢我的英语不好:D
(注意:我的代码包含一个进度条和一个显示每秒下载速度的标签)
(注2:我需要下载大文件,所以我必须使用backroundworker并且在将其写入我的硬盘之前不能使用我的ram来保存文件,我需要直接将文件下载到我的硬盘中)
这是我的下载代码:
FtpWebRequest FTPWbReq = WebRequest.Create(textBox1.Text) as FtpWebRequest;
FTPWbReq.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse FTPWebRes = FTPWbReq.GetResponse() as FtpWebResponse;
bytes_total = Convert.ToUInt64(FTPWebRes.ContentLength);
FTPWebRes.Close();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://"+url);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UseBinary = true;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
using (Stream rs = response.GetResponseStream())
{
using (FileStream ws = new FileStream(folderBrowserDialog1.SelectedPath + "/" + textBox3.Text + enson, FileMode.Create))
{
byte[] buffer = new byte[1024];
int bytesRead = rs.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
FileInfo inen = new FileInfo(folderBrowserDialog1.SelectedPath + "/" + textBox3.Text + enson);
ws.Write(buffer, 0, bytesRead);
bytesRead = rs.Read(buffer, 0, buffer.Length);
progressBar1.Maximum = 2147483646;
progressBar1.Value = Convert.ToInt32((ulong)inen.Length * 2147483646 / bytes_total);
label7.Text = inen.Length.ToString();
if (surehesaplama > 50)
{
if (checkBox1.Checked)
{
if ((inen.Length - anlikalinanbyte) / (surehesaplama * 10) >= ((limit / 1024)-100))
{
Random rastgele = new Random();
int sayi = rastgele.Next(-15, 15);
label1.Text = Convert.ToString((limit / 1024) + sayi);
}
else
{
label1.Text = Convert.ToString((inen.Length - anlikalinanbyte) / (surehesaplama * 10));
}
}
else
{
label1.Text = Convert.ToString((inen.Length - anlikalinanbyte) / (surehesaplama * 10));
}
surehesaplama = 0;
anlikalinanbyte = inen.Length;
}
try
{
if (checkBox1.Checked)
{
FileInfo toplaminen = new FileInfo(folderBrowserDialog1.SelectedPath + "/" + textBox3.Text + enson);
asdfghjkl = (ulong)toplaminen.Length;
try
{
limit =Convert.ToInt32(hizsiniri.Text)*1024;
}
catch (Exception)
{
limit = 50*1024;
}
if (limit<50*1024)
{
limit = 50*1024;
}
if (limtisaniyesayaci!=0)
{
ulong aradakifark = (ulong)toplaminen.Length - suaninen;
while (maxinmesigereken < aradakifark)
{
}
sifirmi = true;
}
else
{
sifirmi = false;
}
}
FileInfo yeniinen = new FileInfo(folderBrowserDialog1.SelectedPath + "/" + textBox3.Text + enson);
suaninen = (ulong)yeniinen.Length;
if (sifirmi)
{
limtisaniyesayaci = 0;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
}
问题是:
- 此代码中我的最大下载速度约为每秒4mb,但我的网速约为每秒13mb。 (如果我使用webclient.webClient.DownloadFileAsync (new uri(myurl),savepath)
我可以获得每秒17mb的下载速度)
- 我无法选择特定的下载速度限制。
- 当我尝试取消下载时,应用程序只是冻结但它没有破碎
问题是如何解决这些问题?