using System;
using System.IO;
using System.Net;


namespace winform1
{
    class DownloadThread
    {
        /// <summary>
        /// 线程开始事件
        /// </summary>
        public event EventHandler threadStartEvent;
        /// <summary>
        /// 线程执行时事件
        /// </summary>
        public event EventHandler threadEvent;
        /// <summary>
        /// 线程结束事件
        /// </summary>
        public event EventHandler threadEndEvent;

        /// <summary>        
        /// c#,.net 下载文件        
        /// </summary>        
        /// <param name="url">下载文件地址</param>       
        /// <param name="filename">下载后的存放地址</param>     
        public void RunMethod(string url, string filename)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //通知主界面,我开始了, response.ContentLength用来设置进度条的最大值
                threadStartEvent.Invoke(response.ContentLength, null);

                Stream st = response.GetResponseStream();
                Stream so = new FileStream(filename, FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte += osize;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, by.Length);

                    //通知主界面我正在执行,totalDownloadedByte表示进度条当前进度
                    threadEvent.Invoke(totalDownloadedByte, null);
                }
                so.Close();
                st.Close();

                //通知主界面我已经完成了
                threadEndEvent.Invoke(null, null);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
