web-dev-qa-db-fra.com

Comment télécharger un fichier depuis un site web en C #

Est-il possible de télécharger un fichier depuis un site Web sous forme d'application Windows et de le placer dans un certain répertoire?

61
S3THST4

Avec le WebClient class :

using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
111
CMS

Utilisation WebClient.DownloadFile :

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}
80
Jon Skeet

Vous devrez peut-être connaître l'état pendant le téléchargement du fichier ou utiliser les informations d'identification avant de faire la demande.

Voici un exemple couvrant ces options:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

Et les fonctions de rappel implémentées comme suit:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - notation Lambda: autre option possible pour gérer les événements

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - On peut faire mieux

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - O

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

Vous pouvez utiliser ce code pour télécharger le fichier d'un site Web sur le bureau:

using System.Net;

WebClient Client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.Zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.Zip");
2
Pouya

Essayez cet exemple:

public void TheDownload(string path)
{
  System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Disposition",
             "attachment; filename=" + toDownload.Name);
  HttpContext.Current.Response.AddHeader("Content-Length",
             toDownload.Length.ToString());
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.WriteFile(patch);
  HttpContext.Current.Response.End();
} 

La mise en œuvre se fait de la manière suivante:

TheDownload("@"c:\Temporal\Test.txt"");

Source: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

0
angelo

Vous pouvez aussi utiliser la méthode DownloadFileAsync dans la classe WebClient. Il télécharge dans un fichier local la ressource avec le 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/

0
turgay