WPF下载和取消下载功能并显示进度条


记录一个小案例:下载和取消下载(还可以用事件与委托的形式实现),但是我没有用,我这个比较简单

话不多说直接上案例:

"XRKAddin.Versions.UpdateVersion"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:XRKAddin.Versions"
             mc:Ignorable="d" xmlns:hc="https://handyorg.github.io/handycontrol"
             Height="500" Width="400" WindowStartupLocation="CenterScreen" WindowStyle="None"
             AllowsTransparency="True" BorderThickness="24" xmlns:wpfanimated="http://wpfanimatedgif.codeplex.com"
            Title="关于" ShowInTaskbar="False" ResizeMode = "NoResize" Loaded="Window_Loaded">
    
        "20" Color="#FF858484" Direction="300" ShadowDepth="0" Opacity="0.5"/>
    
    "#0D6FB8" BorderThickness="1"  >
        
            
                
                
                "../Resources/login/cloud.png"  Opacity=".1" RenderOptions.CacheInvalidationThresholdMinimum="0.5" RenderOptions.CacheInvalidationThresholdMaximum="2.0" RenderOptions.CachingHint="Cache" Viewport="0,0,157,157" ViewportUnits="Absolute" Stretch="Uniform" TileMode="Tile"/>
            
            
                "50"/>
                "400"/>
            
            "0" Orientation="Horizontal" Background="#D8D8D8" Height="50" hc:WindowAttach.IsDragElement="True">
                
                "../Resources/icon_about.png" Width="18" Height="18" Margin="18,0"/>
                "关于" Height="18"/>
                
            
            "1">
                
                    "60"/>
                    "40"/>
                    "40"/>
                    "105"/>
                    "*"/>
                
                "0" Text="Call-Link" Height="20" FontSize="18" FontWeight="Black" HorizontalAlignment="Center"/>
                "1" Name="version" Text="当前版本1.0.1" Height="20" HorizontalAlignment="Center" Foreground="#BDBDBD"/>
                "2" Orientation="Horizontal" HorizontalAlignment="Center" Name="panel1">
                    
                    
                     
                    
                    "image1" wpfanimated:ImageBehavior.AnimatedSource="../Resources/gengxin1.gif" wpfanimated:ImageBehavior.RepeatBehavior="0x" 
                           wpfanimated:ImageBehavior.AnimateInDesignMode="True" wpfanimated:ImageBehavior.AutoStart="True" Height="18" Width="18" Margin="10"/>
                    
                    
                    "image" Source="../Resources/gengxin.png" Width="18" Height="18" Margin="10" Visibility="Collapsed"/>
                    "inspect" Text="正在检查更新" Height="20" HorizontalAlignment="Center" />
                
                "3">
                    
                        "350"/>
                    
                    "Horizontal">
                        
前台页面
   public bool DownloadFile(string URL, string fileName, ProgressBar progressBar1)
        {
            System.IO.Stream stream1 = null;
            System.IO.Stream stream2 = null;
            try
            {
                System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();

                long totalLength = httpWebResponse1.ContentLength;
                if (progressBar1 != null)
                {
                    progressBar1.Maximum = (int)totalLength;
                }
                stream1 = httpWebResponse1.GetResponseStream();
                stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

                long currentLength = 0;
                byte[] by = new byte[1024];
                int osize = stream1.Read(by, 0, (int)by.Length);


                while (osize > 0)
                {
                    if (isDownload)
                    {
                        throw new Exception("手动停止下载!");
                    }

                    //WpfApplication.DispatcherHelper.DoEvents();
                    System.Windows.Forms.Application.DoEvents();
                    currentLength = osize + currentLength;
                    stream2.Write(by, 0, osize);
                    if (progressBar1 != null)
                    {
                        progressBar1.Dispatcher.BeginInvoke((ThreadStart)delegate { progressBar1.Value = (int)currentLength; });
                        //progressBar1.Value = (int)currentLength;
                        //label1.Text = String.Format("{0} / {1}", BytesToString(currentLength), BytesToString(totalLength));
                    }
                    osize = stream1.Read(by, 0, (int)by.Length);
                }


                stream2.Close();
                stream1.Close();

                return (currentLength == totalLength);
            }
            catch
            {
                isDownload = false;
                if (stream1 != null)
                    stream1.Close();
                if (stream2 != null)
                    stream2.Close();
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                return false;
            }
            finally
            {
                isDownload = false;
                stream2.Close();
                stream1.Close();
            }
        }
后台下载功能
 private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            isDownload = true;
            progressbar.Value = 0.0;
            progressbar.Visibility = Visibility.Collapsed;
            this.confirm.IsEnabled = true;
            this.cancel.IsEnabled = false;
        }
取消下载按钮
 private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cancel.Visibility = Visibility.Visible;
                progressbar.Visibility = Visibility.Visible;

                // 重新加载按钮样式
                confirm.Margin = new Thickness(40, 0, 0, 0);
                this.confirm.IsEnabled = false;
                this.cancel.IsEnabled = true;

                string resu = Tool.Get_cookie(configinfo.callLinkserviceurl + "/version/getReleaseVersion/1", null);
                if (resu != "")
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(resu);
                    string code = jo["code"].ToString().ToUpper();
                    if (code == "200")
                    {
                        string url = jo["data"]["downloadUrl"].ToString();
                        string version = jo["data"]["versionFlag"].ToString();
                        if (url != null)
                        {
                            string filename = AppDomain.CurrentDomain.BaseDirectory + "NewVersion" + version + ".exe";
                            if (DownloadFile(url, filename, progressbar))
                            {
                                MessageBox.Show("下载成功!");
                                // 将版本号存入json文件中
                                // Writejson(version);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // 更新失败
                this.image.Visibility = Visibility.Visible;
                this.image1.Visibility = Visibility.Collapsed;
                Uri uri = new Uri(@"../Resources/fail.png", UriKind.Relative);
                this.image.Source = new BitmapImage(uri);
                this.inspect.Text = "更新检查失败";
            }
        }
下载按钮