Risposte:
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
Includi questo spazio dei nomi
using System.Net;
Scarica in modo asincrono e inserisci una ProgressBar per mostrare lo stato del download all'interno dell'interfaccia utente stessa
private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync (
// Param1 = Link of file
new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
// Param2 = Path to save
"D:\\Images\\front_view.jpg"
);
}
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
Utilizzare System.Net.WebClient.DownloadFile
:
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
Classe completa per scaricare un file durante la stampa dello stato sulla console.
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
class FileDownloader
{
private readonly string _url;
private readonly string _fullPathWhereToSave;
private bool _result = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWhereToSave)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWhereToSave = fullPathWhereToSave;
}
public bool 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(@"Downloading file:");
client.DownloadFileAsync(ur, _fullPathWhereToSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWhereToSave);
}
}
catch (Exception e)
{
Console.WriteLine("Was not able to download file!");
Console.Write(e);
return false;
}
finally
{
this._semaphore.Dispose();
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write("\r --> {0}%.", e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download finished!");
_semaphore.Release();
}
public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
Uso:
static void Main(string[] args)
{
var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
Console.WriteLine("Done - success: " + success);
Console.ReadLine();
}
SemaphoreSlim
in questo contesto?
Prova a usare questo:
private void downloadFile(string url)
{
string file = System.IO.Path.GetFileName(url);
WebClient cln = new WebClient();
cln.DownloadFile(url, file);
}
Inoltre è possibile utilizzare il metodo DownloadFileAsync nella classe WebClient. Scarica in un file locale la risorsa con l'URI specificato. Inoltre, questo metodo non blocca il thread chiamante.
Campione:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
Per maggiori informazioni:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
Verificare la presenza di una connessione di rete GetIsNetworkAvailable()
per evitare di creare file vuoti quando non si è connessi a una rete.
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
"D:\\test.txt");
}
}
GetIsNetworkAvailable()
poiché, nella mia esperienza, restituisce troppi falsi positivi.
GetIsNetworkAvailable()
ritornerebbe sempre correttamente. In tal caso puoi usare il System.Net.WebClient().OpenRead(Uri)
metodo per vedere se ritorna quando ti viene dato un url predefinito. Vedi WebClient.OpenRead ()
Il codice seguente contiene la logica per il file di download con il nome originale
private string DownloadFile(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string filename = "";
string destinationpath = Environment;
if (!Directory.Exists(destinationpath))
{
Directory.CreateDirectory(destinationpath);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
{
string path = response.Headers["Content-Disposition"];
if (string.IsNullOrWhiteSpace(path))
{
var uri = new Uri(url);
filename = Path.GetFileName(uri.LocalPath);
}
else
{
ContentDisposition contentDisposition = new ContentDisposition(path);
filename = contentDisposition.FileName;
}
var responseStream = response.GetResponseStream();
using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
{
responseStream.CopyTo(fileStream);
}
}
return Path.Combine(destinationpath, filename);
}
Potrebbe essere necessario conoscere lo stato e aggiornare una ProgressBar durante il download del file o utilizzare le credenziali prima di effettuare la richiesta.
Eccolo qui, un esempio che copre queste opzioni. Sono state usate la notazione lambda e l' interpolazione di stringhe :
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
Secondo la mia ricerca ho scoperto che WebClient.DownloadFileAsync
è il modo migliore per scaricare il file. È disponibile nello System.Net
spazio dei nomi e supporta anche il core .net.
Ecco il codice di esempio per scaricare il file.
using System;
using System.IO;
using System.Net;
using System.ComponentModel;
public class Program
{
public static void Main()
{
new Program().Download("ftp://localhost/test.zip");
}
public void Download(string remoteUri)
{
string FilePath = Directory.GetCurrentDirectory() + "/tepdownload/" + Path.GetFileName(remoteUri); // path where download file to be saved, with filename, here I have taken file name from supplied remote url
using (WebClient client = new WebClient())
{
try
{
if (!Directory.Exists("tepdownload"))
{
Directory.CreateDirectory("tepdownload");
}
Uri uri = new Uri(remoteUri);
//password username of your file server eg. ftp username and password
client.Credentials = new NetworkCredential("username", "password");
//delegate method, which will be called after file download has been complete.
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
//delegate method for progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
// uri is the remote url where filed needs to be downloaded, and FilePath is the location where file to be saved
client.DownloadFileAsync(uri, FilePath);
}
catch (Exception)
{
throw;
}
}
}
public void Extract(object sender, AsyncCompletedEventArgs e)
{
Console.WriteLine("File has been downloaded.");
}
public void ProgessChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
}
}
Con il codice sopra riportato il file verrà scaricato nella tepdownload
cartella della directory del progetto. Si prega di leggere il commento nel codice per capire cosa fa il codice sopra.