Загрузка по списку нескольких файлов с веб-сервера - C#
Формулировка задачи:
При разработе приложения возникла необходимость загрузить по списку несколько файлов с https- вебсервера.
Как сделать загрузку нового файла, только после финиша предыдущего,
в данный момент загрузка происходит всех выбранных файлов одновременно, а прогресбар начинает дергаться, сбрасываться, если загружать 1 файл, то прогресбар работает отлично.
Я использую checkedListBox, в будущем ссылок на файлы будет очень много, если есть способ решения укоротить код или какой нибудь другой способ, всегда буду рад вашему примеру
Тестовый проект прикрепил, а вот весь код проекта:
Находил пару тем по смыслу, но не смог разобраться в них, так как опыта с программированием не так много.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
private void button2_Click(object sender, EventArgs e)
{
if (checkedListBox1.GetItemCheckState(0) == CheckState.Checked)
{
string link = @"http://support.satgate.net/dl_test/dl/5MB.bin"; //ссылка
string downloadFileName = Path.GetFileName("5MB.bin"); //Имя файла
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(link), folderBrowserDialog1.SelectedPath + "" + downloadFileName); //название и можно путь провести, если папки не существует то ее надо создать заранее
}
if (checkedListBox1.GetItemCheckState(1) == CheckState.Checked)
{
string link = @"http://support.satgate.net/dl_test/dl/10MB.bin";
string downloadFileName = Path.GetFileName("10MB.bin");
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(link), folderBrowserDialog1.SelectedPath + "" + downloadFileName);
}
if (checkedListBox1.GetItemCheckState(2) == CheckState.Checked)
{
string link = @"http://support.satgate.net/dl_test/dl/50MB.bin";
string downloadFileName = Path.GetFileName("50MB.bin");
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(link), folderBrowserDialog1.SelectedPath + "" + downloadFileName);
}
if (checkedListBox1.GetItemCheckState(3) == CheckState.Checked)
{
string link = @"http://support.satgate.net/dl_test/dl/100MB.bin";
string downloadFileName = Path.GetFileName("100MB.bin");
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(link), folderBrowserDialog1.SelectedPath + "" + downloadFileName);
}
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
// The event that will trigger when the WebClient is completed
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
string error = e.Error.ToString();
// or
// error = "Your error message here";
MessageBox.Show(error);
return;
}
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
MessageBox.Show("Download completed!");
}
}
}
}Решение задачи: «Загрузка по списку нескольких файлов с веб-сервера»
textual
Листинг программы
// Получить список файлов с вэб-сервера
public static string[] GetHttpFiles(string url)
{
List<string> files = new List<string>(10000);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string html = reader.ReadToEnd();
Regex regex = new Regex("<a href=".*">(?<name>.*)</a>");
MatchCollection matches = regex.Matches(html);
if (matches.Count > 0)
{
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (Match match in matches)
{
if (match.Success)
{
//string[] matchData = match.Groups[0].ToString().Split('"');
//files.Add(matchData[1]);
files.Add(Convert.ToString(match.Groups["name"]));
}
}
}
}
}
return files.ToArray();
}
private void buttonGetFileList_Click(object sender, EventArgs e)
{
checklistFiles.Items.Clear();
foreach (var line in GetHttpFiles(textBoxHttp.Text))
{
if ((line.ToLower() != "description") && (line.ToLower() != "parent directory"))
{
checklistFiles.Items.Add(line, true);
}
}
}