Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am developing Download Manager and I am HttpWebRequest but my progress bar's value is not changing. Can you tell me What is wrong?

I have tried pb.value = (example)
but its not working. I have wrote this line in TASK.Start thred
What can I do??

Thanks in Advance..

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows;
using System.Net;
using System.Threading;
using System.Reflection;

namespace DownloadManager
{
    /// <summary>
    /// Interaction logic for Download.xaml
    /// </summary>
    public partial class Download : Window,INotifyPropertyChanged
    {
        public Download()
        {
            InitializeComponent();
           //this.Loaded += OnLoad;


        }


        private int m_Progress;

        public int Progress
        {
            get { return m_Progress; }
            set
            {
                if (value == m_Progress) return;
                m_Progress = value;


                OnPropertyChanged("Progressb");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyname)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs("Progressb"));


    Application.Current.Dispatcher.Invoke(() => {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Progressb"));
            }, System.Windows.Threading.DispatcherPriority.Background);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Progressb"));
            }
        }
        Uri uri;
        static WebClient client = new WebClient();


       static int row = 0;
        public void download(string link, string path)
        {
            uri = new Uri(link);
            String FileName = System.IO.Path.GetFileName(uri.AbsolutePath);
            client.DownloadFileAsync(uri, path +@"\" + FileName);
            client.DownloadProgressChanged += downloadprogress;
            FileName1.Content = FileName;


        }

        double Percentage;
        public void downloadprogress(object sender, DownloadProgressChangedEventArgs e)
        {
            pb.Minimum = 0;
            double receive = double.Parse(e.BytesReceived.ToString());
            double Filesize = double.Parse(e.TotalBytesToReceive.ToString());
            Percentage = receive / Filesize * 100;
            // a1 = int.Parse(Math.Truncate(Percentage).ToString());
            pb.Value = int.Parse(Math.Truncate(Percentage).ToString());
            //pb1.Value = pb.Value;
            Download download = new Download();
            int p = (int) Percentage;
            MainWindow m = Application.Current.MainWindow as MainWindow;
            m.change(download,p.ToString(),row);

                Status.Content = "Downloading.";
                Status.Content = "Downloading..";
                Status.Content = "Downloading...";

            if (pb.Value == 100)
            {
                row++;
                Status.Content = "Completed";
                Close();


            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
        }



        private volatile bool _allowedToRun;
        private string _source;
        private string _destination;
        private int _chunkSize;
        Download d1;
        private IProgress<double> _progress;


        private Lazy<int> _contentLength;

        public int BytesWritten { get; private set; }
        public int ContentLength { get { return _contentLength.Value; } }

        public bool Done { get { return ContentLength == BytesWritten; } }

        public Download(string source, string destination, int chunkSize, IProgress<double> progress = null)
        {
            _allowedToRun = true;

            _source = source;
            _destination = destination;
            _chunkSize = chunkSize;
            _contentLength = new Lazy<int>(() => Convert.ToInt32(GetContentLength()));
            _progress = progress;

            BytesWritten = 0;
        }

        private long GetContentLength()
        {
            var request = (HttpWebRequest)WebRequest.Create(_source);
            request.Method = "HEAD";

            using (var response = request.GetResponse())
                return response.ContentLength;
        }

        static public int p9;
        private async Task Start(int range)
        {

            if (!_allowedToRun)
                throw new InvalidOperationException();

            var request = (HttpWebRequest)WebRequest.Create(_source);
            request.Method = "GET";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.AddRange(range);


            using (var response = await request.GetResponseAsync())
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (var fs = new FileStream(_destination, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                        while (_allowedToRun)
                        {
                            var buffer = new byte[_chunkSize];
                            var bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length);

                            if (bytesRead == 0) break;

                            await fs.WriteAsync(buffer, 0, bytesRead);
                            BytesWritten += bytesRead;
                            double receive = double.Parse(BytesWritten.ToString());

                            double Filesize = 5761048;
                            double Percentage = receive / Filesize * 100;

                            // a1 = int.Parse(Math.Truncate(Percentage).ToString());
                            //pb.Value = int.Parse(Math.Truncate(Percentage).ToString());
                            //progress(int.Parse(Math.Truncate(Percentage).ToString()));
                            // MessageBox.Show(int.Parse(Math.Truncate(Percentage).ToString()) + "Done");
                            int per = int.Parse(Math.Truncate(Percentage).ToString());
                            Progress = per;
                            await Task.Delay(20);

                        }
                        await fs.FlushAsync();
                    }
                }


            }

        }

        public Task Start()
        {
            _allowedToRun = true;

            return Start(BytesWritten);
        }

        public void Pause1()
        {
            _allowedToRun = false;
        }




        void MakeButton2()
        {
            Button b2 = new Button();
            //  b2.AddHandler(Button.ClickEvent, new RoutedEventHandler(Onb2Click2));
            // MessageBox.Show("HI");
        // b2.Click += new RoutedEventHandler(Onb2Click2);
           // b2.AddHandler(Button.ClickEvent, new RoutedEventHandler(Onb2Click2));
           // Onb2Click2(null, RoutedEventArgs.Empty);
           // Onb2Click2(this, new RoutedEventArgs());

           //Onb2Click2(new object(), new RoutedEventArgs());

        }

         object sender;


        public void Onb2Click2(object sender, RoutedEventArgs e)
        {

           //    Button b = b2(sender);
           // MessageBox.Show("Hi");
          // ProgressBar pb= e.Source as ProgressBar;
          //  pb.Value = p;

           // MessageBox.Show(p + "");
        }
        void OnLoad(object sender, RoutedEventArgs e)
        {

           // pb.Value = p;


        }


        private void Pause_Click(object sender, RoutedEventArgs e)
        {

            //change();
            //pb.Value = p;
            int m=0;


                    //Onb2Click2(sender, e);
                   //    Thread.Sleep(5000);

               // m = perc();
                   }


    }


}
Posted
Updated 30-Jan-22 13:34pm
v2
Comments
M Imran Ansari 29-Jan-22 14:58pm    
share complete code is not a good idea. review the code and share the problematic area.
Luc Pattyn 29-Jan-22 17:24pm    
Not sure it wouldbe sufficient, but I would most certainly execute client.DownloadProgressChanged += downloadprogress; before calling DownloadFileAsync
lmoelleb 30-Jan-22 9:03am    
Won't read through all of that code, but what is "Progressb"? Always use nameof(Progress) or similar construction to avoid a typo. Here you are probably telling the progress indicator "Hey, Progressb is changed", and the progress bar then goes "I do not care about Progressb, let me know when Progress changes!"
Nehal Chaudhari 30-Jan-22 23:17pm    
Thank You sir

1 solution

private int m_Progress;

public int Progress
{
    get { return m_Progress; }
    set
    {
        if (value == m_Progress) return;
        m_Progress = value;

        OnPropertyChanged("Progressb");
    }
}


Magic string like OnPropertyChanged("Progressb"); allow coding errors to creep in. This line will cause the binding to fail.

Best practice is not to use magic strings but instead to use nameof:

OnPropertyChanged(nameof(Progress));

Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900