Hey, I'm working on a simple command line program to download some files. I already made a Win Forms version, but wanted to do a command line version. The Win Forms app works exactly as it should, but I'm having some trouble with the command line app. Heres my code:

class Program
        public static WebClient wc;

        static void Main(string[] args)
            if (args.Length > 0)
                wc = new WebClient();
                wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");

                string[] getName = args[0].Split('/');
                int eN = getName.Length;
                string fileName = getName[eN-1];

                string dFileName = String.Format(@"{0}", fileName);

                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
                wc.DownloadFileAsync(new Uri(args[0]), dFileName);

                Console.Write("\n -- No URL specified. Correct usage: winget url_of_file");
                Console.Write("\n\n -- Press any key to exit. -- ");

        static void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            ConsoleFunctions.Code.RenderConsoleProgress(e.ProgressPercentage, '#', ConsoleColor.Green, "Downloading...");

        static void Completed(object sender, AsyncCompletedEventArgs e)
            Console.WriteLine("Download Completed.");

Okay, so my problem is that this just doesn't work! I don't see the progress bar, the Completed event doesn't fire and the file downloads instantly (even if its large), and is just completely empty. I've been trying to figure out why this is, but I just can't work it out. I should also probably add that if I use 'DownloadFile()' rather than 'DownloadFileAsync()' the download completes just fine.

Many thanks,


5 Years
Discussion Span
Last Post by satnav_8

string dFileName = String.Format(@"{0}", fileName);

What are you trying to acheive with this line?

Also, I can't see anything wrong with your code in particular.

Could you provide the code for your RenderConsoleProgress method so that I can test the code?



In my opinion, the curent behaviour is because you launch an async action (new thread) and then do not wait for completion on current.

After launching the DownloadFileAsync, you must do a

while (wc.IsBusy){ Application.Doevents();} 

to wait for completion in the current thread, then you can finish. (see this)

Hope this helps

Votes + Comments
Ah yes, I missed this. Effectively the op will start the download and then it will exit.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.