Comment télécharger un fichier depuis une URL en C #?

Quel est un moyen simple de télécharger un fichier à partir d’un chemin d’URL?

using (var client = new WebClient()) { client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg"); } 

Inclure cet espace de noms

 using System.Net; 

Télécharger de manière asynchrone et placer un ProgressBar pour afficher l’état du téléchargement dans le thread de l’interface utilisateur lui-même

 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://soffr.miximages.com/c%23/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; } 

Utilisez System.Net.WebClient.DownloadFile :

 ssortingng remoteUri = "http://www.contoso.com/library/homepage/images/"; ssortingng fileName = "ms-banner.gif", mySsortingngWebResource = null; // Create a new WebClient instance. using (WebClient myWebClient = new WebClient()) { mySsortingngWebResource = remoteUri + fileName; // Download the Web resource and save it into the current filesystem folder. myWebClient.DownloadFile(mySsortingngWebResource, fileName); } 
 using System.Net; WebClient webClient = new WebClient(); webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt"); 

Classe complète pour télécharger un fichier tout en imprimant l’état à la console.

 using System; using System.ComponentModel; using System.IO; using System.Net; using System.Threading; class FileDownloader { private readonly ssortingng _url; private readonly ssortingng _fullPathWhereToSave; private bool _result = false; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0); public FileDownloader(ssortingng url, ssortingng fullPathWhereToSave) { if (ssortingng.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); if (ssortingng.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.ToSsortingng()); } Console.WriteLine(Environment.NewLine + "Download finished!"); _semaphore.Release(); } public static bool DownloadFile(ssortingng url, ssortingng fullPathWhereToSave, int timeoutInMilliSec) { return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec); } } 

Usage:

 static void Main(ssortingng[] args) { var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec); Console.WriteLine("Done - success: " + success); Console.ReadLine(); } 

Vous pouvez également utiliser la méthode DownloadFileAsync dans la classe WebClient. Il télécharge dans un fichier local la ressource avec l’URI spécifié. De plus, cette méthode ne bloque pas le thread appelant.

Échantillon:

  webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg"); 

Pour plus d’informations:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

GetIsNetworkAvailable() une connexion réseau à l’aide de GetIsNetworkAvailable() pour éviter de créer des fichiers vides lorsque vous GetIsNetworkAvailable() pas connecté à un réseau.

 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"); } } 

Essayez d’utiliser ceci:

 private void downloadFile(ssortingng url) { ssortingng file = System.IO.Path.GetFileName(url); WebClient cln = new WebClient(); cln.DownloadFile(url, file); } 

Le code ci-dessous contient la logique du fichier de téléchargement avec le nom d’origine

 private ssortingng DownloadFile(ssortingng url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); ssortingng filename = ""; ssortingng destinationpath = Environment; if (!Directory.Exists(destinationpath)) { Directory.CreateDirectory(destinationpath); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result) { ssortingng path = response.Headers["Content-Disposition"]; if (ssortingng.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); } 

Vous devrez peut-être connaître l’état et mettre à jour un ProgressBar pendant le téléchargement du fichier ou utiliser les informations d’identification avant de faire la demande.

Voici un exemple qui couvre ces options. La notation Lambda et l’ interpolation de chaîne ont été utilisées:

 using System.Net; // ... using (WebClient client = new WebClient()) { Uri ur = new Uri("http://soffr.miximages.com/c%23/img.jpg"); //client.Credentials = new NetworkCredential("username", "password"); Ssortingng credentials = Convert.ToBase64Ssortingng(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"); } 

Au lieu de le télécharger dans un fichier local, vous pouvez le convertir en object de stream d’octets et le stocker sous la forme d’un BLOB varbinary (MAX) dans SQL Server.

Étant donné que votre table ressemble à:

 CREATE TABLE [dbo].[Documents]( [DocumentId] [int] IDENTITY(1,1) NOT NULL, [DocumentTypeId] [int] NOT NULL, [UploadedByMemberId] [int] NOT NULL, [DocumentTitle] [nvarchar](200) NOT NULL, [DocumentDescription] [nvarchar](2000) NULL, [FileName] [nvarchar](200) NOT NULL, [DateUploaded] [datetime] NOT NULL, [ApprovedForUsers] [bit] NOT NULL, [ApprovedByMemberId] [int] NOT NULL, [ApprovedDate] [datetime] NULL, [DocBLOB] [varbinary](max) NOT NULL, CONSTRAINT [PK_Documents] PRIMARY KEY CLUSTERED ( [DocumentId] ASC ) SqlParameter Title = new SqlParameter("@Title", SqlDbType.VarChar); SqlParameter FileName = new SqlParameter("@FileName", SqlDbType.VarChar); SqlParameter DateFileUploaded = new SqlParameter("@DateUploaded", SqlDbType.VarChar); SqlParameter DocBLOB = new SqlParameter("@DocBLOB", SqlDbType.VarBinary); command.Parameters.Add(Title); command.Parameters.Add(FileName); command.Parameters.Add(DateFileUploaded); command.Parameters.Add(DocBLOB); mySsortingngWebResource = remoteUri + dataReader["FileName"].ToSsortingng(); imgdownload = myWebClient.DownloadData(mySsortingngWebResource); querySQL = @"INSERT INTO Documents(DocumentTypeId, UploadedByMemberId, DocumentTitle, DocumentDescription, FileName, DateUploaded, ApprovedForUsers, ApprovedByMemberId, ApprovedDate, DocBLOB) VALUES(1, 0, @Title, '', @FileName, @DateUploaded, 1, 0, GETDATE(), @DocBLOB);"; Title.Value = dataReader["Title"].ToSsortingng().Replace("'", "''").Replace("\"", ""); FileName.Value = dataReader["FileName"].ToSsortingng().Replace("'", "''").Replace("\"", ""); DateFileUploaded.Value = dataReader["DateUploaded"].ToSsortingng(); DocBLOB.Value = imgdownload; command.CommandText = querySQL; command.ExecuteNonQuery();