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

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

话不多说直接上案例:

<Window x:Class="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">
    <Window.Effect>
        <DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="300" ShadowDepth="0" Opacity="0.5"/>
    </Window.Effect>
    <Border BorderBrush="#0D6FB8" BorderThickness="1"  >
        <Grid>
            <Grid.Background>
                <!--<ImageBrush ImageSource="pack://SiteOfOrigin:,,,/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"/>-->
                
                <ImageBrush ImageSource="../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"/>
            </Grid.Background>
            <Grid.RowDefinitions>
                <RowDefinition Height="50"/>
                <RowDefinition Height="400"/>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="0" Orientation="Horizontal" Background="#D8D8D8" Height="50" hc:WindowAttach.IsDragElement="True">
                <!--<Image Source="pack://SiteOfOrigin:,,,/Resources/icon_about.png" Width="18" Height="18" Margin="18,0"/>-->
                <Image Source="../Resources/icon_about.png" Width="18" Height="18" Margin="18,0"/>
                <TextBlock Text="关于" Height="18"/>
                <Button Margin="230,10" Background="#D8D8D8" BorderBrush="#D8D8D8" Click="Close">
                    <Button.Content>
                        <!--<Image Source="pack://SiteOfOrigin:,,,/Resources/icon_close.png" Width="12" Height="12"/>-->
                        <Image Source="../Resources/icon_close.png" Width="12" Height="12"/>
                    </Button.Content>
                </Button>
            </StackPanel>
            <Grid Grid.Row="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="60"/>
                    <RowDefinition Height="40"/>
                    <RowDefinition Height="40"/>
                    <RowDefinition Height="105"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="0" Text="Call-Link" Height="20" FontSize="18" FontWeight="Black" HorizontalAlignment="Center"/>
                <TextBlock Grid.Row="1" Name="version" Text="当前版本1.0.1" Height="20" HorizontalAlignment="Center" Foreground="#BDBDBD"/>
                <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Name="panel1">
                    <!--<MediaElement Name="wait_gif" MediaEnded="MediaElement_MediaEnded" Source="pack://SiteOfOrigin:,,,/Resources/20210730134302.gif" Width="18" Height="18" Margin="10" Opacity="0.5"/>-->
                    <!--显示gif图片的方式-->
                    <!--<Image x:Name="image1" wpfanimated:ImageBehavior.AnimatedSource="pack://SiteOfOrigin:,,,/Resources/20210730134302.gif" wpfanimated:ImageBehavior.RepeatBehavior="0x" 
                           wpfanimated:ImageBehavior.AnimateInDesignMode="True" wpfanimated:ImageBehavior.AutoStart="True" Height="18" Width="18" Margin="10"/>--> 
                    
                    <Image x:Name="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 x:Name="image" Source="pack://SiteOfOrigin:,,,/Resources/gengxin.png" Width="18" Height="18" Margin="10" Visibility="Collapsed"/>-->
                    
                    <Image x:Name="image" Source="../Resources/gengxin.png" Width="18" Height="18" Margin="10" Visibility="Collapsed"/>
                    <TextBlock x:Name="inspect" Text="正在检查更新" Height="20" HorizontalAlignment="Center" />
                </StackPanel>
                <Grid Grid.Row="3">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="350"/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Orientation="Horizontal">
                        <Button Grid.Column="0" Name="cancel" Width="80" Height="40" Margin="80,0,0,0" Content="取消" Style="{StaticResource ButtonPrimary}" Click="Cancel_Click" Visibility="Collapsed"/>
                        <Button Grid.Column="1" Name="confirm" Width="80" Height="40" Margin="140,0,0,0" Content="更新" Style="{StaticResource ButtonPrimary}" Click="Confirm_Click" Visibility="Visible"/>
                    </StackPanel>
                </Grid>
                <Grid Grid.Row="4">
                    <StackPanel Margin="20,20,20,0">
                        <ProgressBar x:Name="progressbar" Style="{DynamicResource ProgressBarSuccess}" Width="250" Visibility="Collapsed"></ProgressBar>
                        <!--<TextBlock x:Name="label1" Text="ProgressBarSuccess" Margin="30,0"></TextBlock>-->
                    </StackPanel>
                    <!--<Image Source="pack://SiteOfOrigin:,,,/Resources/bg.png"/>-->
                    <Image Source="../Resources/bg.png"/>
                    <StackPanel Margin="70">
                        <!--<Image Source="pack://SiteOfOrigin:,,,/Resources/logo.png" Width="102" Height="19"/>-->
                        <Image Source="../Resources/logo.png" Width="102" Height="19"/>
                    </StackPanel>
                    <StackPanel>
                        <TextBlock Height="20" HorizontalAlignment="Center" Margin="0,100">
                         <Hyperlink Name="link" NavigateUri="http://www.sunmooc.cn/" ToolTip="欢迎访问,向日葵教育" Click="Hyperlink_Click">www.sunmooc.cn</Hyperlink>
                        </TextBlock>
                    </StackPanel>
                </Grid>
            </Grid>
        </Grid>
    </Border>
</Window>
前台页面
   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 = "更新检查失败";
            }
        }
下载按钮

 

posted @ 2021-08-09 17:24  江南-烟雨  阅读(372)  评论(0编辑  收藏  举报