C#错误使用进度条显示从Internet下载和运行文件的进度

时间:2013-04-18 23:02:32

标签: c# progress-bar runtime-error webclient

好吧所以我是编程的新手,我想制作一个带有进度条的工具条,它会显示从互联网上获取并打开的文件的进度,这里是代码snipplet http://pastebin.com/3EKrFb4K并且它不会在代码中给出一个错误,但是当我调试它时,当我尝试下载并打开文件(一旦它甚至不做)时,这就说了http://gyazo.com/44634914669d81b1c20d3d26f2dd3ad8我想知道它是否只是简单的东西或者我写的代码不会工作?它是一个工具条进度条所以我必须做一些特别的事情或什么?请提前帮助和感谢。

1 个答案:

答案 0 :(得分:0)

问题是您在下载文件之前打开文件:

WebClient web = new WebClient();             web.DownloadFileAsync(new Uri(direct_exe_from_url),filepath); //这个方法是异步的             web.DownloadProgressChanged + = new DownloadProgressChangedEventHandler(web_DownloadProgressChanged);
            的Process.Start(文件路径); //你还在下载时打开文件。

您需要在downloadFileCompleted处理程序中执行进程启动。

这应该有效:

private void startBotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string directoryPath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\";
            string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21FB6AD2A0A1EB413347302A46C5FB1A39599DF740D6&directstart=1";

            WebClient web = new WebClient();
            web.DownloadFileAsync(new Uri(direct_exe_from_url), filepath);
            web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(web_DownloadProgressChanged);    
            web.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback);
        }

        void web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            ProgressBar1.Value = e.ProgressPercentage;
        }

         void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
        {
            string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
            Process.Start(filepath);

        }