服务器更新软件

来源:互联网 发布:鹏业算量软件好吗 编辑:程序博客网 时间:2024/05/16 15:21

private string g_DownloadSavePath= "C:\\xx";

       private string g_CurLoad = "";

       private string g_DownLoadPath = "http://xx.xx.xx//xx//xx ";

       private string g_SerPath = "http:// xx.xx.xx ";

       List<string>_list = newList<string>();

       int m_Times= 0;

 

       publicMainWindow()

       {

            InitializeComponent();

            GetRefreshSize();

            InitLoad();

            Refresh();

       }

 

//获取更新的文件大小 只更新改动过的文件主要是dll、exe、txt、config等

//refreSize.txt保存要下载的文件的总大小

       voidGetRefreshSize()

       {

            System.Net.WebClient myWebClient = newSystem.Net.WebClient();

           myWebClient.DownloadFile(g_DownLoadPath+"//refreSize.txt",g_DownloadSavePath+"\\refreSize.txt");

            if(File.Exists(g_DownloadSavePath +"\\refreSize.txt"))

            {

                string str = File.ReadAllText(g_DownloadSavePath +"\\refreSize.txt");

                allLen = double.Parse(str);

            }

       }

 

//有可能会遇到下载失败的情况 因此需要判断

voidRefresh()

       {

            m_Times = 0;

            _pf = new Window1();

            Thread thread2 = new Thread(new ThreadStart(delegate

            {

                do

                {

                    plusLen = 0;

                    Analyhtml(g_DownLoadPath);

                    m_Times++;

                }

                while (!IsAgain() && m_Times < 6);

                _isfinish = true;

 

           }));

            thread2.Priority =ThreadPriority.Highest;

            thread2.Start();

            ShowProgress();

 

            if (m_Times < 5)

            {

               ReplaceFile(g_DownloadSavePath);

                DeleteFloder(g_DownloadSavePath);

                btnDownAgain.Width = 0;

                txtResult.Text = "更新完成";

            }

            else

            {

                _isfinish = false;

                btnDownAgain.Width = 200;

                txtResult.Text = "更新失败";

            }

       }

 

#region test

       void test()

       {

            try {

            string filePath = "C:\\Windows\\file.txt";

            StreamWriter sr;

            sr = File.AppendText(filePath);

            for (int i = 0; i < _list.Count; i++)

            {

                sr.WriteLine(_list[i]);sr.WriteLine(g_DownloadSavePath);

            }

            sr.Close();

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

       }

       #endregion

 

       #region recycle

       boolIsAgain()

       {

            if (_list.Count == 0)

            {

                return true;

            }

            if (_list.Count > 0)

            {

                for (int i = 0; i < _list.Count; i++)

                {

                    if (_list[i].Contains(".dll") || _list[i].Contains(".pdb") || _list[i].Contains(".exe") || _list[i].Contains(".db") || _list[i].Contains(".myconfig"))//该语句根据个人需求定不一定只针对上述格式

                    {

                        return false;

                    }

                }

            }

            return true;

       }

       #endregion

 

voidInitLoad()

       {

            DirectoryInfo topDir =System.IO.Directory.GetParent(System.Environment.CurrentDirectory);

          // g_CurLoad = topDir.Parent.FullName;

            g_CurLoad = topDir.FullName;

            //g_CurLoad= "C:\\Users\\Administrator\\Desktop";

            if (!Directory.Exists(g_DownloadSavePath))

            {

               Directory.CreateDirectory(g_DownloadSavePath);

            }

            else

            {

               DeleteFloder(g_DownloadSavePath);

            }

       }

 

       voidAnalyhtml(stringurlPath)

       {

            List<string> directorys =new List<string>();

          

            HtmlWeb webClient = new HtmlWeb();

            HtmlDocument doc = new HtmlDocument();

            try {

                doc = webClient.Load(urlPath);

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            HtmlNodeCollection hrefList =doc.DocumentNode.SelectNodes(".//a[@href]");

            bool bFirst = true;

            if (hrefList != null)

            {

                foreach (HtmlNode hrefin hrefList)

                {

                    if (!bFirst)

                    {

                        HtmlAttribute att =href.Attributes["href"];

                        int index =att.Value.LastIndexOf("/");

                        string savePath ="";

                        string downPath ="";

 

                        if(att.Value.Contains(".")&& !(att.Value.Contains("/.vs")))

                        {

                            att.Value =att.Value.Remove(index + 1);

                            savePath =g_DownloadSavePath + att.Value.Replace("/AIO/AIOMachine","").Replace("/","\\") + href.InnerText;

                            downPath =g_SerPath + att.Value.Replace("/","//") + href.InnerText;//该语句可解决中文乱码问题

                        }

                        else

                        {

                            savePath =g_DownloadSavePath + att.Value.Replace("/AIO/AIOMachine","").Replace("/","\\");

                            downPath =g_SerPath + att.Value.Replace("/","//");

                        }

 

                        if(href.InnerText.Contains("."))

                        {

                           DownLoadFileFromServer(downPath, savePath);

                        }

                        else

                        {

//由于http协议可能无法判断服务器里的某个路径是否是文件夹 因此才有该步骤  当然 也可能有办法判断是否是文件夹 只不过我没找到方法

                            if(!Directory.Exists(savePath))

                            {

                               Directory.CreateDirectory(savePath);

                            }

                            Analyhtml(downPath);

                        }

                    }

                    bFirst = false;

                }

            }

       }

 

double lLen =0;//当前下载的文件大小

       double plusLen= 0;//已经下载的总大小

       double allLen= 0;//要下载的文件总大小(放在服务器上的更新的项目大小)

       private voidDownLoadFileFromServer(string Url, string SavePath)

       {

            WebClient client = new WebClient();

            string Path = "";

            Path = SavePath;

            try

            {

                if (Path.Contains(".myconfig"))

               {

                    Path = Path.Replace(".myconfig",".config");

                }

                client.DownloadFile(Url, Path);

                if (File.Exists(Path))

                {

                    FileInfo fin = new FileInfo(Path);

                    lLen = (double)fin.Length / 1024;

                    plusLen += (long)lLen;

                }

                return;

            }

            catch

            {

                _list.Add(Url);

                return;

            }

       }

       

 

       #region file

       voidReplaceFile(stringsavePath)

       {

            savePath = savePath + "\\Debug";

            if (!Directory.Exists(savePath))

            {

                MessageBox.Show("找不到指定路径!");

                return;

            }

            DirectoryInfo sDir = newDirectoryInfo(savePath);

            DirectoryInfo[] subDirArray =sDir.GetDirectories();

            FileInfo[] fileArray =sDir.GetFiles();

 

            List<string> fileList =new List<string>();

            List<string> dirList =new List<string>();

            foreach (FileInfo filein fileArray)

            {

                string name = file.FullName;

                int iIndex = name.IndexOf("Debug");

                name = name.Remove(0, iIndex -1);

                fileList.Add(name);

            }

            foreach (DirectoryInfo dirin subDirArray)

            {

                string name = dir.FullName;

                int iIndex = name.IndexOf("Debug");

                name = name.Remove(0, iIndex -1);

                dirList.Add(name);

            }

            DeleteFloderList(dirList);

            CopyFileList(fileList);

            CopyFloderList(dirList);

       }

       //删除文件

       voidDeleteFileList(List<string> fileList)

       {

            if(fileList==null)

            {

                return;

            }

            for (int i = 0; i < fileList.Count; i++)

            {

                DeleteFile(fileList[i]);

            }

       }

       void DeleteFile(string filePath)

       {

            if (File.Exists(filePath))

            {

                File.Delete(filePath);

            }

       }

 

       //删除文件夹

       voidDeleteFloderList(List<string> dirList)

       {

            string path = "";

            if (dirList != null && dirList.Count > 0)

            {

                int iIndex = dirList[0].IndexOf("Debug");

                path = dirList[0].Remove(0,iIndex);

            }

            else

            {

                return;

           }

            for (int i = 0; i < dirList.Count; i++)

            {

                path = g_CurLoad + "\\" + path;

                DeleteFloder(path);

            }

       }

       voidDeleteFloder(stringdestPath)

       {

            if (!Directory.Exists(destPath))

            {

                return;

            }

            DirectoryInfo sDir = newDirectoryInfo(destPath);

            FileInfo[] fileArray =sDir.GetFiles();

            foreach (FileInfo filein fileArray)

            {

               file.Delete();

            }

            DirectoryInfo dDir = newDirectoryInfo(destPath);

            DirectoryInfo[] subDirArray =sDir.GetDirectories();

            foreach (DirectoryInfo subDirin subDirArray)

            {

                DeleteFloder(subDir.FullName);

            }

       }

 

//拷贝文件

       voidCopyFileList(List<string>filePath)

       {

            if (filePath!=null && filePath.Count > 0)

            {

            }

            else

            {

               return;

            }

            for (int i = 0; i < filePath.Count; i++)

            {

              

                string destPath = g_CurLoad + filePath[i];

                string sourPath = g_DownloadSavePath + filePath[i];

                CopyFile(destPath, sourPath);

            }

       }

       voidCopyFile(stringdestPath,stringsourPath)

       {

            File.Copy(sourPath, destPath, true);

       }

 

       //拷贝文件夹

       voidCopyFloderList(List<string> dirPath)

       {

            if (dirPath != null && dirPath.Count > 0)

            {

            }

            else

            {

                return;

            }

            for (int i = 0; i < dirPath.Count; i++)

            {

                string destPath = g_CurLoad +dirPath[i];

                string sourPath = g_DownloadSavePath + dirPath[i];

                CopyFloder(destPath, sourPath);

            }

       }

       voidCopyFloder(stringdestPath,stringsourPath)

       {

           if (!Directory.Exists(destPath))

            {

               Directory.CreateDirectory(destPath);

            }

            DirectoryInfo sDir = newDirectoryInfo(sourPath);

            FileInfo[] fileArray =sDir.GetFiles();

            foreach (FileInfo filein fileArray)

            {

                file.CopyTo(destPath + "\\" + file.Name, true);

            }

            DirectoryInfo dDir = newDirectoryInfo(destPath);

            DirectoryInfo[] subDirArray =sDir.GetDirectories();

            foreach (DirectoryInfo subDirin subDirArray)

            {

                CopyFloder(subDir.FullName,destPath + "\\" +subDir.Name);

            }

       }

 

voidDownLoadFloder(string Url,string path, string savePath)

       {

            if (!Directory.Exists(savePath))

            {

               Directory.CreateDirectory(savePath);

            }

            DirectoryInfo sDir = newDirectoryInfo(path);

            FileInfo[] fileArray =sDir.GetFiles();

            foreach (FileInfo filein fileArray)

            {

                DownLoadFileFromServer(Url +file.Name, savePath + file.Name);

            }

            DirectoryInfo dDir = newDirectoryInfo(path);

            DirectoryInfo[] subDirArray =sDir.GetDirectories();

           foreach (DirectoryInfo subDirin subDirArray)

            {

                DownLoadFloder(Url +subDir.Name, subDir.FullName, savePath + subDir.Name);

            }

       }

       #endregion

 

//关闭服务和开启服务 我是调用自己写的类库 设置的管理员权限  当然 你也可以自己写

网上有很多开启 关闭服务的方法

//我更新的软件在电脑上有看门狗程序, 因此需要关闭服务,有些软件更新不需要该步骤

  #region server

       //关闭服务

       voidShutDownServer()

       {

            try

            {

                ServiceController[] services =ServiceController.GetServices();

                foreach (ServiceController servicein services)

                {

                    if (service.ServiceName =="xx")

                    {

                        string sampleExeName =Environment.CurrentDirectory +"\\ConsoleAppServiceManage.exe";

                       Process.Start(sampleExeName, "0");//

                    }

                }

           }

            catch

            {

 

            }

       }

       //打开服务

       voidOpenServer()

       {

            try

            {

                ServiceController[] services =ServiceController.GetServices();

                foreach (ServiceController servicein services)

                {

                    if (service.ServiceName =="xx ")

                    {

                        string sampleExeName =Environment.CurrentDirectory +"\\ConsoleAppServiceManage.exe";

                       Process.Start(sampleExeName, "1");//

                    }

                }

            }

            catch

            {

            }

       }

       #endregion

 

//就是一个普通的进度条 用线程让他不停走就行了 当然 进度值是根据先前定义的plusLen 和allLen实现的

#region 进度条

       Window1 _pf;

       bool_isfinish = false;

       private void RefreshProgess()

       {

            try

            {

                Thread thread = new Thread(new ThreadStart(delegate

                   {

                       while (!_isfinish)

                       {

                           double progress = lLen;

                           double barValue = 0;

                           barValue = plusLen /allLen * 100;

                          _pf.Dispatcher.Invoke(new Action(delegate

                           {

                              _pf.SetProgressValue(progress, barValue);

                           }));

                           Thread.Sleep(50);

                       }

                       _pf.Dispatcher.Invoke(new Action(delegate

                       {

                           _pf.Close();

                       }));

                   }));

                thread.Priority =ThreadPriority.BelowNormal;

                thread.Start();

            }

            catch

            {

 

            }

       }

       private void ShowProgress()

       {

            try

            {

                _pf.Dispatcher.Invoke(new Action(delegate

                {

                    RefreshProgess();

                    bool? isdone = _pf.ShowDialog();

                    if (!(bool)isdone)

                    {

                        _isfinish = true;

                    }

                }));

            }

            catch

            {

            }

       }

       #endregion

 

 

       private void ConfireOK(object sender,RoutedEventArgs e)

       {

            OpenServer();

           System.Environment.Exit(System.Environment.ExitCode);

       }

 

       private void DownloadAgain(object sender,RoutedEventArgs e)

       {

            Refresh();

       }

   }

}

原创粉丝点击