using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
namespace Ultra_Script
{
class FileDownloader
{
privatereadonlystring _url;
privatereadonlystring _fullPathWheretoSave;
privatebool _result = false;
privatereadonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWheretoSave)
{
if (string.IsNullOrEmpty(url)) thrownew ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWheretoSave)) thrownew ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWheretoSave = fullPathWheretoSave;
}
publicbool StartDownload(int timeout)
{
try
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWheretoSave));
if (File.Exists(_fullPathWheretoSave))
{
File.Delete(_fullPathWheretoSave);
}
using (WebClient client = new WebClient())
{
var ur = new Uri(_url);
//client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadFileCompleted += WebClientDownloadCompleted;
Console.WriteLine(@"Stahuji potrebne soubory:");
client.DownloadFileAsync(ur, _fullPathWheretoSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWheretoSave);
}
}
catch (Exception e)
{
Console.WriteLine("Cant download file");
Console.Write(e);
returnfalse;
}
finally
{
this._semaphore.Dispose();
}
}
privatevoid WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write($"/r --> {e.ProgressPercentage}%");
}
privatevoid WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download Finished!");
_semaphore.Release();
}
publicstaticbool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
returnnew FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
}
Když tu funkci spustím z konzole vše funguje jak má, ale jakmile jí
zavolám přes to tlačítko na formu, tak dostanu jenom "Stahuju potrebne
soubory", běží do konce timeout a pak se to vypne.
Někdo by tušil kde by mohl být problém?
Díky za všechny rady,
Honza
Zkusil jsem: Smazat semaphore metodu - nepomohlo.
Chci docílit: Aplikace která sloužení k automatizování stahování a
instalaci základního SW počítače.
Děláme co je v našich silách, aby byly zdejší diskuze co nejkvalitnější. Proto do nich také mohou přispívat pouze registrovaní členové. Pro zapojení do diskuze se přihlas. Pokud ještě nemáš účet, zaregistruj se, je to zdarma.