简体   繁体   English

使用WebClient在WPF应用程序中下载文件

[英]Using webclient to download file in a WPF application

I'm making a WPF application. 我正在制作WPF应用程序。 I'm using WebClient to download files. 我正在使用WebClient下载文件。 I have a list of the name of the files that should be downloaded from a current path. 我有应该从当前路径下载的文件名称的列表。 I use an foreach to iterate through each name and then download each file sequency. 我使用一个foreach来遍历每个名​​称,然后下载每个文件序列。 The name of the file i get from a torrent file which i decode. 我从洪流文件中解码得到的文件名。

public class DownloadGameFile
{
    private DownloadTorrentFile DLTorrent;

    //List of file that already exist
    private List<string> ExistFile = new List<string>();
    DirectoryInfo fileInfo;
    private volatile bool _completed;

    private string savePath = @"C:\Program Files (x86)\program\Client\package\downloads\";

    public DownloadGameFile()
    {
        DLTorrent = new DownloadTorrentFile();
        fileInfo = new DirectoryInfo(savePath);
    }
    public bool StartDownload(int torrentId)
    {
        try
        {
            DLTorrent.DecodeTorrent(torrentId);


            //File info from a Directory
            FileInfo[] files = fileInfo.GetFiles();

            foreach (FileInfo i in files)
            {
                Console.WriteLine("Files exit ");
                if (DLTorrent.GameInfomation[i.Name] != i.Length)
                {
                    i.Delete();
                }
                else
                {
                    Console.WriteLine("add files ");
                    ExistFile.Add(i.Name);
                }
            }
            //Make a list which file not downloaded yet
            var res = DLTorrent.GameInfomation.Keys.Except(ExistFile);

            foreach (var x in res)
            {
                Console.WriteLine(x);
            }

            foreach (var x in res)
            {
                DownloadProtocol("http://cdn.path.com/rental/" + torrentId + "/" + x, savePath + x);
            }

            return true;

        }
        catch
        {
            return false;
        }
    }

    public void DownloadProtocol(string address, string location)
    {
        WebClient client = new WebClient();
        Uri Uri = new Uri(address);

        client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
        client.DownloadFileAsync(Uri, location);


    }


    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
        }
        else
        {

            Console.WriteLine("Download completed!");
        }
    }

This code work fine in an Console app with a current thread blocker. 此代码在具有当前线程阻止程序的控制台应用程序中可以正常工作。 But when I use the same code in an WPF app It doesn't. 但是,当我在WPF应用程序中使用相同的代码时,事实并非如此。 I'm using a button to execute the StartDownload() function, but when I do that it start downloading all the files at the same time. 我正在使用一个按钮来执行StartDownload()函数,但是当我这样做时,它将开始同时下载所有文件。 Example the first file get 3% done and then it switch to another file and so on. 例如,第一个文件完成3%,然后切换到另一个文件,依此类推。 I really don't know why this isn't working. 我真的不知道为什么这不起作用。

Have you considered not using .DownloadFileAsync? 您是否考虑过不使用.DownloadFileAsync? You can try .DownloadFile and start DownloadProtocol() with a single background thread. 您可以尝试.DownloadFile并使用单个后台线程启动DownloadProtocol()。 Although I think you'll have to rethink your DownloadProgress output. 尽管我认为您必须重新考虑DownloadProgress输出。

I do something very similar within a winform. 我在winform中做了非常相似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM