Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Программирование и базы данных (http://forum.oszone.net/forumdisplay.php?f=21)
-   -   С# Загрузка файла с отображением процесса загрузки (http://forum.oszone.net/showthread.php?t=354871)

nwss 31-01-2024 00:50 3023489

С# Загрузка файла с отображением процесса загрузки
 
Добрый день.

С#, Net Framework 4.5
Хочу создать консольное приложение которое загрузит файл с отображением процесса загрузки.

Код:

using System;
using System.ComponentModel;
using System.IO;
using System.Net;

public class Program
{
    public static void Main()
    {
        new Program().Download("https://github.com/deemru/Chromium-Gost/releases/download/121.0.6167.85/chromium-gost-121.0.6167.85-windows-386.zip");
    }
    public void Download(string remoteUri)
    {
        string FilePath = Directory.GetCurrentDirectory() + "/temp/" + Path.GetFileName(remoteUri);
        using (WebClient client = new WebClient())
        {
            if (!Directory.Exists("temp"))
            {
                Directory.CreateDirectory("temp");
            }
            Uri uri = new Uri(remoteUri);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
            client.DownloadFileAsync(uri, FilePath);
        }
    }
    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}%.");
    }
}

Но загрузка не происходит. Ошибок не дает. Создает папку темп, в ней название целевого файла с весом 0 байт и закрывается.
В таком виде работает, но хотелось бы отображение процесса загрузки.

Код:

using System;
using System.Net;

namespace test
{
    internal class Program
    {
        static void Main1(string[] args)
        {
            string URI = "https://github.com/deemru/Chromium-Gost/releases/download/121.0.6167.85/chromium-gost-121.0.6167.85-windows-386.zip";
            using (var client = new WebClient())
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                client.DownloadFile(URI , "chromium-gost-121.0.6167.85-windows-386.zip");
            }
            Console.WriteLine("Готово");
            Console.ReadKey();
        }
    }
}

Подскажите, что не так с первым кодом?

Sham 31-01-2024 08:35 3023495

Цитата:

Цитата nwss
client.DownloadFileAsync(uri, FilePath); »

видимо не блокирует и сразу после неё вызывается client.Dispose(). Во втором как раз DownloadFile не асинхронный.

nwss 31-01-2024 18:37 3023525

Цитата:

Цитата Sham
client.Dispose() »

а с чего он вызывается-то?

то что не асинхронный работает я понимаю, но мне хочется отображение процесса загрузки.
пока что сделал вот такое убожество, но выглядит не так красиво, как хотелось бы.
Код:

using System;
using System.IO;
using System.Net;

namespace test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string URI = "https://github.com/deemru/Chromium-Gost/releases/download/121.0.6167.85/chromium-gost-121.0.6167.85-windows-386.zip";
            using (var client = new WebClient())
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                client.DownloadFileAsync(new Uri(URI), "chromium-gost-121.0.6167.85-windows-386.zip");
                while (client.IsBusy)
                {
                    long length = new FileInfo("chromium-gost-121.0.6167.85-windows-386.zip").Length;
                    Console.Clear();
                    Console.WriteLine("Еще качаем \"{0}\" Мбайт", length / 1024 / 1024);
                    System.Threading.Thread.Sleep(100);
                }
            }
            Console.WriteLine("Готово");
            Console.ReadKey();
        }
    }
}


Sham 31-01-2024 19:42 3023526

хотя сам WebClient и не IDisposable, но наследует от такого (Component). Для чего тогда using(){}?
Цитата:

Цитата nwss
while (client.IsBusy) »

гляньте в сторону DownloadFileTaskAsync - он возвращает Task, на котором можно .wait().

Sham 31-01-2024 20:04 3023527

у меня этот вариант нормально отработал (компилировал под .net framework в win10)
Код:

using System;
using System.ComponentModel;
using System.IO;
using System.Net;

public class Program
{
    public static void Main()
    {
        new Program().Download("https://github.com/deemru/Chromium-Gost/releases/download/121.0.6167.85/chromium-gost-121.0.6167.85-windows-386.zip");
    }
    public void Download(string remoteUri)
    {
        string FilePath = Directory.GetCurrentDirectory() + "/temp/" + Path.GetFileName(remoteUri);
        using (WebClient client = new WebClient())
        {
            if (!Directory.Exists("temp"))
            {
                Directory.CreateDirectory("temp");
            }
            Uri uri = new Uri(remoteUri);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            client.DownloadFileTaskAsync(uri, FilePath).Wait();
        }
    }
    public void Extract(object sender, AsyncCompletedEventArgs e)
    {
        Console.Write("\nFile has been downloaded.\n");
    }
    public void ProgessChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.Write("\rDownload status: " + e.ProgressPercentage + "%.");
    }
}



Время: 11:33.

Время: 11:33.
© OSzone.net 2001-