Подтвердить что ты не робот

Как загрузить файл с веб-сайта в С#

Можно ли загрузить файл с веб-сайта в форме приложения Windows и поместить его в определенный каталог?

4b9b3361

Ответ 1

С класс WebClient:

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

Ответ 2

Используйте WebClient.DownloadFile:

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

Ответ 3

Конечно, вы просто используете HttpWebRequest.

После настройки HttpWebRequest вы можете сохранить поток ответов в файл StreamWriter (либо BinaryWriter, либо TextWriter в зависимости от типа mimetype.), и у вас есть файл на жестком диске диск.

EDIT: Забыл WebClient. Это работает хорошо, если только вам нужно использовать GET для извлечения файла. Если сайт требует от вас POST информации к нему, вам придется использовать HttpWebRequest, поэтому я оставляю свой ответ.

Ответ 4

Вам может потребоваться узнать статус во время загрузки файла или использовать учетные данные перед выполнением запроса.

Вот пример, который охватывает следующие параметры:

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

Ответ 5

Вы можете использовать этот код для загрузки файла с веб-сайта на рабочий стол:

using System.Net;

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

Ответ 6

Попробуйте этот пример:

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

Ответ 7

Также вы можете использовать метод 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/