Как скачать файл с веб-сайта в C# [закрыт]
можно ли загрузить файл с веб-сайта в форме приложения Windows и поместить его в определенный каталог?
7 ответов:
using System.Net; //... WebClient Client = new WebClient (); Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
использовать
WebClient.DownloadFile:using (WebClient client = new WebClient()) { client.DownloadFile("http://csharpindepth.com/Reviews.aspx", @"c:\Users\Jon\Test\foo.txt"); }
возможно, Вам потребуется узнать статус во время загрузки файла или использовать учетные данные перед выполнением запроса.
вот пример, который охватывает такие варианты:
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"); }и функции обратного вызова выглядит следующим образом:
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!"); }лямбда-нотация: другой возможный вариант для обработки событий
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!"); });мы можем сделать лучше
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!"); };или
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!"); };
конечно, вы просто используете
HttpWebRequest.после
HttpWebRequestнастройка, вы можете сохранить поток ответов в файлStreamWriter(либоBinaryWriterилиTextWriterв зависимости от типа.) и у вас есть файл на жестком диске.EDIT: забыл о
WebClient. Это работает хорошо, если только вам не нужно использоватьGETчтобы получить ваш файл. Если сайт требует от васPOSTинформация к нему, вы должны будете использоватьHttpWebRequest, Так что я ухожу мой ответ вверх.
вы можете использовать этот код для загрузки файла с сайта на рабочий стол:
using System.Net; WebClient Client = new WebClient (); client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");
попробуйте этот пример:
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(); }реализация осуществляется следующим образом:
TheDownload("@"c:\Temporal\Test.txt"");Источник:http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html
также вы можете использовать
DownloadFileAsyncметодWebClientкласса. Он загружает в локальный файл ресурс с указаннымURI. Также Этот метод не блокирует вызывающий поток.пример:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");для получения дополнительной информации:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/