winform自动更新并实现文件的批量异步下载

时间:2022-01-26 15:58:54

public partial class update : Form
    {
        private WebClient client;
        int downfilenum = 0; //已下载文件数
        int downlistnum = 0;//总下载文件数
        List<string> list;
        private string URl;
        private string fileName;
        private const string applicationFile = "Setup";

public update()
        {
            InitializeComponent();
        }
        //检测网络状态
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        private void update_Load(object sender, EventArgs e)
        {
            if (isConnected())
            {
                client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.Proxy = WebRequest.DefaultWebProxy;
                client.Proxy.Credentials = new NetworkCredential();
                updateFile();
            }
            else
            {
                lblMsg.Text = "网络连接异常,请联系管理员处理";
            }
        }
        /// <summary>
        /// 检测网络状态
        /// </summary>
        private bool isConnected()
        {
            int I = 0;
            bool state = InternetGetConnectedState(out I, 0);
            return state;
        }
        /// <summary>
        /// 获取xml文件,判断是否升级
        /// </summary>
        /// <param name="Dir"></param>
        /// <returns></returns>
        private string getSoftUpdate()
        {
            if (!File.Exists(Application.StartupPath + @"\\update.xml"))
            {
                return "nofile";
            }
            DateTime newDateTime;
            try
            {
                SrmUpdate.updateSoapClient s = new SrmUpdate.updateSoapClient();
                newDateTime = Convert.ToDateTime(s.GetSoftUpDateTime());//获取服务器最新更新日期
            }
            catch (Exception)
            {

throw;
            }
            DateTime oldDateTime;
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\\update.xml");
            oldDateTime = Convert.ToDateTime(doc.SelectSingleNode("/AutoUpdate/SoftUpdateTime").Attributes["Date"].Value);
            return newDateTime >= oldDateTime ? "true" : "false";
        }
        /// <summary>
        /// 开始下载文件
        /// </summary>
        private void updateFile()
        {
            //判断系统有无更新,如果需要升级系统,开始下载
            string isUpdate = getSoftUpdate();
            if (isUpdate == "true")
            {
                lblMsg.Text = "检测到版本有更新,准备升级";
                progressBar1.Visible = true;
                startDownload();
            }
            else if (isUpdate == "false")
            {
                lblMsg.Text = "无需更新,直接启动系统";
                runSystem();
            }
            else if (isUpdate == "nofile")
            {
                lblMsg.Text = "缺少系统文件,请您联系管理员处理";
            }
        }
        /// <summary>
        /// 下载完成调用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            downfilenum++;
            if (client != null) { client.CancelAsync(); }
            if (downfilenum < downlistnum) downLoadFile(list[downfilenum].ToString()); //下载剩余的
            if (downfilenum == downlistnum) { init(); } //初始化
        }
        //下载某个文件
        private void downLoadFile(string fileName)
        {
            downLoad(URl + fileName, Application.StartupPath + "\\temp\\" + fileName, true); //异步下载远程文件
        }
        /// <summary>
        /// 下载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            int a = e.ProgressPercentage;
            progressBar1.Value = a;
            lblMsg.Text = a + "% Downloading... ";
        }
        
        /// <summary>
        /// HTTP下载远程文件并保存本地的函数
        /// </summary>
        private void downLoad(string downAddress, string savePath, Boolean Async)
        {
            DirectoryInfo di = Directory.GetParent(savePath);
            if (!di.Exists) di.Create();

WebClient client = new WebClient();  //再次new 避免WebClient不能I/O并发          
            if (Async)
            { //异步下载
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(downAddress), savePath);
            }
            else client.DownloadFile(new Uri(downAddress), savePath);
        }
        /// <summary>
        /// 开始下载
        /// </summary>
        private void startDownload()
        {
            SrmUpdate.updateSoapClient ws = new SrmUpdate.updateSoapClient();
            URl = ws.GetSoftUpdateUrl();
            list = ws.GetSoftUpdateFileList();
            downlistnum = list.Count;
            fileName = list[0].Substring(list[0].LastIndexOf("/") + 1, list[0].Length - list[0].LastIndexOf("/") - 1);
            downLoad(URl + list[0], Application.StartupPath + "\\temp\\" + fileName, true);
        }
        private void init()
        {
            string curdir = Application.StartupPath;
            DirectoryInfo theFolder = new DirectoryInfo(curdir + @"\temp");
            if (theFolder.Exists)
            {
                copyDirectory(curdir + @"\temp", curdir);
            }

if (Directory.Exists(curdir + @"\temp\")) Directory.Delete(curdir + @"\temp\", true); //删除临时目录
            runSystem();
        }
        /// <summary>
        /// 复制文件夹中的所有文件到指定文件夹
        /// </summary>
        /// <param name="DirectoryPath">源文件夹路径</param>
        /// <param name="DirAddress">保存路径</param>
        private void copyDirectory(string DirectoryPath, string DirAddress)//复制文件夹,
        {
            if(!Directory.Exists(DirAddress)) Directory.CreateDirectory(DirAddress);
            DirectoryInfo DirectoryArray = new DirectoryInfo(DirectoryPath);
            FileInfo[] Files = DirectoryArray.GetFiles();//获取该文件夹下的文件列表
            DirectoryInfo[] Directorys = DirectoryArray.GetDirectories();//获取该文件夹下的文件夹列表
            foreach (FileInfo theFile in Files)//逐个复制文件     
            {
                //如果临时文件夹下存在与应用程序所在目录下的文件同名的文件,则删除应用程序目录下的文件   
                if (File.Exists(DirAddress + "\\" + Path.GetFileName(theFile.FullName)))
                    File.Delete(DirAddress + "\\" + Path.GetFileName(theFile.FullName));
                //将临时文件夹的文件移到应用程序所在的目录下   
                File.Copy(theFile.FullName, DirAddress + "\\" + Path.GetFileName(theFile.FullName));
            }
            foreach (DirectoryInfo Dir in Directorys)//逐个获取文件夹名称,并递归调用方法本身     
            {
                copyDirectory(DirectoryPath + "\\" + Dir.Name, DirAddress + "\\" + Dir.Name);
            }
        }
        /// <summary>
        /// 启动主程序
        /// </summary>
        private void runSystem()
        {
            //启动安装程序  
            this.lblMsg.Text = "正在启动主程序....";
            System.Diagnostics.Process.Start(Application.StartupPath + @"\SRMClientAppLoader.exe");
            this.Close();
        }
    }