• C# winfrom桌面应用实现自动更新


    实现方式/思路:FTP文件(应用程序包)下载,解压

    帮助类:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    
    namespace AutoUpdate.Helper
    {
        public class ProcessHelper
        {
            private static ProcessHelper instance;
            public static ProcessHelper Instance
            {
                get
                {
                    if (instance == null) instance = new ProcessHelper();
                    return ProcessHelper.instance;
                }
            }
    
            /// <summary>
            /// 关闭进程
            /// </summary>
            /// <param name="processName">进程名</param>
            public void KillProcessByName(string processName)
            {
                try
                {
                    Process[] myproc = Process.GetProcesses();
                    foreach (Process item in myproc)
                    {
                        if (item.ProcessName == processName)
                        {
                            item.CloseMainWindow();
                            item.Kill();
                        }
                    }
                }
                catch { return; }
            }
    
            /// <summary>
            /// 启动进程
            /// </summary>
            /// <param name="processName">进程名,完全限定名</param>
            public void StartProcessByName(string processName)
            {
                System.Diagnostics.Process.Start(processName);
                //Process process = new Process();//声明一个进程类对象
                //process.StartInfo.FileName = processName;//Application.StartupPath + "\AutoUpdate.exe";
                //process.Start();
            }
    
            public void StartProcessByName(string processName,string param)
            {
                //System.Diagnostics.Process.Start(processName);
                Process p = new Process();//声明一个进程类对象
                p.StartInfo.FileName = processName;// Application.StartupPath + "\AutoUpdate.exe";
                p.StartInfo.UseShellExecute = true;
                p.StartInfo.Arguments = param;
                p.Start();
            }
    
    
        }
    }
    
    using System;
    using System.IO;
    using System.Diagnostics;
    using Microsoft.Win32;
    using ICSharpCode.SharpZipLib.Checksums;
    using ICSharpCode.SharpZipLib.Zip;
    
    namespace AutoUpdate.Helper
    {
        public class SharpZip
        {
            public SharpZip()
            { }
    
            /// <summary>
            /// 压缩
            /// </summary> 
            /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
            /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
            public static void PackFiles(string filename, string directory)
            {
                try
                {
                    FastZip fz = new FastZip();
                    fz.CreateEmptyDirectories = true;
                    fz.CreateZip(filename, directory, true, "");
                    fz = null;
                }
                catch (Exception)
                {
                    throw;
                }
            }
    
            /// <summary>
            /// 解压缩
            /// </summary>
            /// <param name="file">待解压文件名(包含物理路径)</param>
            /// <param name="targetdir"> 解压到哪个目录中(包含物理路径)</param>
            public static bool UnpackFiles(string file, string targetdir)
            {
                try
                {
                    if (!Directory.Exists(targetdir))
                    {
                        Directory.CreateDirectory(targetdir);
                    }
                    ZipInputStream s = new ZipInputStream(File.OpenRead(file));
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName != String.Empty)
                        {
                            Directory.CreateDirectory(targetdir + directoryName);
                        }
                        if (fileName != String.Empty)
                        {
                            //FileStream streamWriter = File.Create(targetdir + theEntry.Name);
                            FileStream streamWriter = File.Create(theEntry.Name);
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            streamWriter.Close();
                        }
                    }
                    s.Close();
                    return true;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    
        public class ClassZip
        {
            #region 私有方法
            /// <summary>
            /// 递归压缩文件夹方法
            /// </summary>
            private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
            {
                bool res = true;
                string[] folders, filenames;
                ZipEntry entry = null;
                FileStream fs = null;
                Crc32 crc = new Crc32();
                try
                {
                    entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
                    s.PutNextEntry(entry);
                    s.Flush();
                    filenames = Directory.GetFiles(FolderToZip);
                    foreach (string file in filenames)
                    {
                        fs = File.OpenRead(file);
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
                catch
                {
                    res = false;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                    if (entry != null)
                    {
                        entry = null;
                    }
                    GC.Collect();
                    GC.Collect(1);
                }
                folders = Directory.GetDirectories(FolderToZip);
                foreach (string folder in folders)
                {
                    if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                    {
                        return false;
                    }
                }
                return res;
            }
    
            /// <summary>
            /// 压缩目录
            /// </summary>
            /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
            /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
            private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
            {
                bool res;
                if (!Directory.Exists(FolderToZip))
                {
                    return false;
                }
                ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
                s.SetLevel(level);
                res = ZipFileDictory(FolderToZip, s, "");
                s.Finish();
                s.Close();
                return res;
            }
    
            /// <summary>
            /// 压缩文件
            /// </summary>
            /// <param name="FileToZip">要进行压缩的文件名</param>
            /// <param name="ZipedFile">压缩后生成的压缩文件名</param>
            private static bool ZipFile(string FileToZip, string ZipedFile, int level)
            {
                if (!File.Exists(FileToZip))
                {
                    throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
                }
                FileStream ZipFile = null;
                ZipOutputStream ZipStream = null;
                ZipEntry ZipEntry = null;
                bool res = true;
                try
                {
                    ZipFile = File.OpenRead(FileToZip);
                    byte[] buffer = new byte[ZipFile.Length];
                    ZipFile.Read(buffer, 0, buffer.Length);
                    ZipFile.Close();
    
                    ZipFile = File.Create(ZipedFile);
                    ZipStream = new ZipOutputStream(ZipFile);
                    ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                    ZipStream.PutNextEntry(ZipEntry);
                    ZipStream.SetLevel(level);
    
                    ZipStream.Write(buffer, 0, buffer.Length);
                }
                catch
                {
                    res = false;
                }
                finally
                {
                    if (ZipEntry != null)
                    {
                        ZipEntry = null;
                    }
                    if (ZipStream != null)
                    {
                        ZipStream.Finish();
                        ZipStream.Close();
                    }
                    if (ZipFile != null)
                    {
                        ZipFile.Close();
                        ZipFile = null;
                    }
                    GC.Collect();
                    GC.Collect(1);
                }
                return res;
            }
            #endregion
    
            /// <summary>
            /// 压缩
            /// </summary>
            /// <param name="FileToZip">待压缩的文件目录</param>
            /// <param name="ZipedFile">生成的目标文件</param>
            /// <param name="level">6</param>
            public static bool Zip(String FileToZip, String ZipedFile, int level)
            {
                if (Directory.Exists(FileToZip))
                {
                    return ZipFileDictory(FileToZip, ZipedFile, level);
                }
                else if (File.Exists(FileToZip))
                {
                    return ZipFile(FileToZip, ZipedFile, level);
                }
                else
                {
                    return false;
                }
            }
    
            /// <summary>
            /// 解压
            /// </summary>
            /// <param name="FileToUpZip">待解压的文件</param>
            /// <param name="ZipedFolder">解压目标存放目录</param>
            public static void UnZip(string FileToUpZip, string ZipedFolder)
            {
                if (!File.Exists(FileToUpZip))
                {
                    return;
                }
                if (!Directory.Exists(ZipedFolder))
                {
                    Directory.CreateDirectory(ZipedFolder);
                }
                ZipInputStream s = null;
                ZipEntry theEntry = null;
                string fileName;
                FileStream streamWriter = null;
                try
                {
                    s = new ZipInputStream(File.OpenRead(FileToUpZip));
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        if (theEntry.Name != String.Empty)
                        {
                            fileName = Path.Combine(ZipedFolder, theEntry.Name);
                            if (fileName.EndsWith("/") || fileName.EndsWith("\"))
                            {
                                Directory.CreateDirectory(fileName);
                                continue;
                            }
                            streamWriter = File.Create(fileName);
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                        streamWriter = null;
                    }
                    if (theEntry != null)
                    {
                        theEntry = null;
                    }
                    if (s != null)
                    {
                        s.Close();
                        s = null;
                    }
                    GC.Collect();
                    GC.Collect(1);
                }
            }
        }
    
        public class ZipHelper
        {
            #region 私有变量
            String the_rar;
            RegistryKey the_Reg;
            Object the_Obj;
            String the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            #endregion
    
            /// <summary>
            /// 压缩
            /// </summary>
            /// <param name="zipname">要解压的文件名</param>
            /// <param name="zippath">要压缩的文件目录</param>
            /// <param name="dirpath">初始目录</param>
            public void EnZip(string zipname, string zippath, string dirpath)
            {
                try
                {
                    the_Reg = Registry.ClassesRoot.OpenSubKey(@"ApplicationsWinRAR.exeShellOpenCommand");
                    the_Obj = the_Reg.GetValue("");
                    the_rar = the_Obj.ToString();
                    the_Reg.Close();
                    the_rar = the_rar.Substring(1, the_rar.Length - 7);
                    the_Info = " a    " + zipname + "  " + zippath;
                    the_StartInfo = new ProcessStartInfo();
                    the_StartInfo.FileName = the_rar;
                    the_StartInfo.Arguments = the_Info;
                    the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    the_StartInfo.WorkingDirectory = dirpath;
                    the_Process = new Process();
                    the_Process.StartInfo = the_StartInfo;
                    the_Process.Start();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
    
            /// <summary>
            /// 解压缩
            /// </summary>
            /// <param name="zipname">要解压的文件名</param>
            /// <param name="zippath">要解压的文件路径</param>
            public void DeZip(string zipname, string zippath)
            {
                try
                {
                    the_Reg = Registry.ClassesRoot.OpenSubKey(@"ApplicationsWinRar.exeShellOpenCommand");
                    the_Obj = the_Reg.GetValue("");
                    the_rar = the_Obj.ToString();
                    the_Reg.Close();
                    the_rar = the_rar.Substring(1, the_rar.Length - 7);
                    the_Info = " X " + zipname + " " + zippath;
                    the_StartInfo = new ProcessStartInfo();
                    the_StartInfo.FileName = the_rar;
                    the_StartInfo.Arguments = the_Info;
                    the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    the_Process = new Process();
                    the_Process.StartInfo = the_StartInfo;
                    the_Process.Start();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
    
    }
    
    
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Windows.Forms;
    
    namespace AutoUpdate.Helper
    {
        public class UpdateHelper
        {
            private static UpdateHelper instance;
            public static UpdateHelper Instance
            {
                get
                {
                    if (instance == null) instance = new UpdateHelper();
                    return UpdateHelper.instance;
                }
            }
    
            //基本设置
            private string FTPFilePath = @"ftp://" + ConfigurationManager.AppSettings["FTPFilePath"];    //目标路径
            private string FtpServerPort = ConfigurationManager.AppSettings["FtpServerPort"];    //ftp IP地址
            private string FtpServerIP = ConfigurationManager.AppSettings["FtpServerIP"];    //ftp IP地址
            private string FtpServerUserName = ConfigurationManager.AppSettings["FtpServerUserName"];   //ftp用户名
            private string FtpServerPassword = ConfigurationManager.AppSettings["FtpServerPassword"];   //ftp密码
    
            //获取ftp上面的文件和文件夹
            public string[] GetFileList(string dir)
            {
                string[] downloadFiles;
                StringBuilder result = new StringBuilder();
                FtpWebRequest request;
                try
                {
                    request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPFilePath));
                    request.UseBinary = true;
                    request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);//设置用户名和密码
                    request.Method = WebRequestMethods.Ftp.ListDirectory;
                    request.UseBinary = true;
    
                    WebResponse response = request.GetResponse();
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("
    ");
                        Console.WriteLine(line);
                        line = reader.ReadLine();
                    }
                    // to remove the trailing '
    '
                    result.Remove(result.ToString().LastIndexOf('
    '), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('
    ');
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取ftp上面的文件和文件夹:" + ex.Message);
                    downloadFiles = null;
                    return downloadFiles;
                }
            }
    
            /// <summary>
            /// 获取文件大小
            /// </summary>
            /// <param name="file">ip服务器下的相对路径</param>
            /// <returns>文件大小</returns>
            public int GetFileSize(string file)
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest request;
                try
                {
                    request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPFilePath + file));
                    request.UseBinary = true;
                    request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);//设置用户名和密码
                    request.Method = WebRequestMethods.Ftp.GetFileSize;
    
                    return (int)request.GetResponse().ContentLength;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取文件大小出错:" + ex.Message);
                    return -1;
                }
            }
    
            /// <summary>
            /// 文件上传
            /// </summary>
            /// <param name="filePath">原路径(绝对路径)包括文件名</param>
            /// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
            public void FileUpLoad(string filePath, string objPath = "")
            {
                try
                {
                    string url = FTPFilePath;
                    if (objPath != "") url += objPath + "/";
                    try
                    {
    
                        FtpWebRequest reqFTP = null;
                        //待上传的文件 (全路径)
                        try
                        {
                            FileInfo fileInfo = new FileInfo(filePath);
                            using (FileStream fs = fileInfo.OpenRead())
                            {
                                long length = fs.Length;
                                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
                                //设置连接到FTP的帐号密码
                                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                                //设置请求完成后是否保持连接
                                reqFTP.KeepAlive = false;
                                //指定执行命令
                                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                                //指定数据传输类型
                                reqFTP.UseBinary = true;
    
                                using (Stream stream = reqFTP.GetRequestStream())
                                {
                                    //设置缓冲大小
                                    int BufferLength = 5120;
                                    byte[] b = new byte[BufferLength];
                                    int i;
                                    while ((i = fs.Read(b, 0, BufferLength)) > 0)
                                    {
                                        stream.Write(b, 0, i);
                                    }
                                    Console.WriteLine("上传文件成功");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("上传文件失败错误为" + ex.Message);
                        }
                        finally
                        {
    
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("上传文件失败错误为" + ex.Message);
                    }
                    finally
                    {
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("上传文件失败错误为" + ex.Message);
                }
            }
    
            /// <summary>
            /// 删除文件
            /// </summary>
            /// <param name="fileName">服务器下的相对路径 包括文件名</param>
            public void DeleteFileName(string fileName)
            {
                try
                {
                    FileInfo fileInf = new FileInfo(FtpServerIP + "" + fileName);
                    string uri = FTPFilePath + fileName;
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // 指定数据传输类型
                    reqFTP.UseBinary = true;
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    // 默认为true,连接不会被关闭
                    // 在一个命令之后被执行
                    reqFTP.KeepAlive = false;
                    // 指定执行什么命令
                    reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("删除文件出错:" + ex.Message);
                }
            }
    
            /// <summary>
            /// 新建目录 上一级必须先存在
            /// </summary>
            /// <param name="dirName">服务器下的相对路径</param>
            public void MakeDir(string dirName)
            {
                try
                {
                    string uri = FTPFilePath + dirName;
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // 指定数据传输类型
                    reqFTP.UseBinary = true;
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("创建目录出错:" + ex.Message);
                }
            }
    
            /// <summary>
            /// 删除目录 上一级必须先存在
            /// </summary>
            /// <param name="dirName">服务器下的相对路径</param>
            public void DelDir(string dirName)
            {
                try
                {
                    string uri = FTPFilePath + dirName;
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("删除目录出错:" + ex.Message);
                }
            }
    
            /// <summary>
            /// 从ftp服务器上获得文件夹列表
            /// </summary>
            /// <param name="RequedstPath">服务器下的相对路径</param>
            /// <returns></returns>
            public List<string> GetDirctory(string RequedstPath)
            {
                List<string> strs = new List<string>();
                try
                {
                    string uri = FTPFilePath + RequedstPath;   //目标路径 path为服务器地址
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    WebResponse response = reqFTP.GetResponse();
                    StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        if (line.Contains("<DIR>"))
                        {
                            string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                            strs.Add(msg);
                        }
                        line = reader.ReadLine();
                    }
                    reader.Close();
                    response.Close();
                    return strs;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取目录出错:" + ex.Message);
                }
                return strs;
            }
    
            /// <summary>
            /// 从ftp服务器上获得文件列表
            /// </summary>
            /// <param name="RequedstPath">服务器下的相对路径</param>
            /// <returns></returns>
            public List<string> GetFile(string RequedstPath)
            {
                List<string> strs = new List<string>();
                try
                {
                    string uri = FTPFilePath + RequedstPath;   //目标路径 path为服务器地址
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    WebResponse response = reqFTP.GetResponse();
                    StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
    
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        if (!line.Contains("<DIR>"))
                        {
                            string msg = line.Substring(39).Trim();
                            strs.Add(msg);
                        }
                        line = reader.ReadLine();
                    }
                    reader.Close();
                    response.Close();
                    return strs;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取文件出错:" + ex.Message);
                }
                return strs;
            }
    
            /// <summary>
            /// 从ftp服务器上下载文件的功能  
            /// </summary>
            /// <param name="fileName">文件名称</param>
            public void Download(string fileName)
            {
                FtpWebRequest reqFTP;
                try
                {
                    string filePath = Application.StartupPath;
                    FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
                    string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    long cl = response.ContentLength;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 解压文件
            /// </summary>
            /// <param name="fileName">文件名</param>
            /// <param name="initPath">路径(不含文件名)</param>
            public void DownloadDir(string fileName,string initPath)
            {
                FtpWebRequest reqFTP;
                try
                {
                    string filePath = initPath;// Application.StartupPath;
                    FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
                    string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    long cl = response.ContentLength;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 从ftp服务器上下载文件的功能  
            /// </summary>
            /// <param name="fileName">文件名称</param>
            /// <param name="targetPath">存放目标位置+文件名称</param>
            public void Download(string fileName, string targetPath)
            {
                FtpWebRequest reqFTP;
                try
                {
                    string filePath = Application.StartupPath;
                    //FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
                    FileStream outputStream = new FileStream(targetPath, FileMode.Create);
                    string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    long cl = response.ContentLength;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 用FTP方式上传文件
            /// </summary>
            /// <param name="fileName"></param>
            /// <param name="uploadUrl"></param>
            /// <param name="msg"></param>
            public void Upload(string fileName, string uploadUrl)
            {
                Stream requestStream = null;
                FileStream fileStream = null;
                FtpWebResponse response = null; try
                {
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uploadUrl);
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                    request.Proxy = null;
                    requestStream = request.GetRequestStream();
                    fileStream = File.Open(fileName, FileMode.Open);
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while (true)
                    {
                        bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0) break;
    
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                    requestStream.Close();
                    response = (FtpWebResponse)request.GetResponse();
                }
                catch (UriFormatException ex)
                {
    
                }
                catch (IOException ex)
                {
    
                }
                catch (WebException ex)
                {
    
                }
                finally
                {
                    if (response != null) response.Close();
                    if (fileStream != null) fileStream.Close();
                    if (requestStream != null) requestStream.Close();
                }
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace AutoUpdate.Helper
    {
        public class VarHelper
        {
            private static VarHelper instance;
            public static VarHelper Instance
            {
                get
                {
                    if (instance == null) instance = new VarHelper();
                    return VarHelper.instance;
                }
            }
    
            //初始路径 + 自动更新程序名称 + 主程序名称 
            //string param = fullPath + ","
            //    + "AutoUpdate\AutoUpdate.exe," //自动更新程序
            //    + "Debug\AutoUpdateApp.exe,"//主程序
            //    + "Debug";//下载包
            /// <summary>
            /// 需要更新的文件夹  初始路径 
            /// </summary>
            public string InitPath = "";
            /// <summary>
            /// 自动更新程序名称 
            /// </summary>
            public string AutoUpdateExe = "";
            /// <summary>
            /// 主程序名称
            /// </summary>
            public string MainExe = "";
            /// <summary>
            /// 下载包
            /// </summary>
            public string DownDir = "";
        }
    }
    

    自动更新程序:

    using AutoUpdate.Helper;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows.Forms;
    using ZB.QueueSys.Common;
    
    namespace AutoUpdate
    {
        public partial class MainForm : Form
        {
            public MainForm()
            {
                InitializeComponent();
            }
    
            private void MainForm_Load(object sender, EventArgs e)
            {
                UpdateApp();
            }
    
            private void UpdateApp()
            {
                this.probarWatting.Style = ProgressBarStyle.Marquee;
                this.probarWatting.Show();
    
                try
                {
                    #region 注释代码
                    //NewMethod();
    
                    //    DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}....", Application.StartupPath));
                    //    string fullPath = di.FullName;
                    //    string param = fullPath + ","
                    //+ "AutoUpdate\AutoUpdate.exe," //自动更新程序
                    //+ "Debug\AutoUpdateApp.exe,"//主程序
                    //+ "Debug";//下载包
    
                    //    VarHelper.Instance.InitPath = param[0];
                    //    VarHelper.Instance.AutoUpdateExe = param[1];
                    //    VarHelper.Instance.MainExe = param[2];
                    //    VarHelper.Instance.DownDir = param[3];
                    #endregion
    
                    string fileZip = VarHelper.Instance.InitPath + VarHelper.Instance.DownDir;//+ "\QueueSys.zip";
                    string target = VarHelper.Instance.InitPath + "\" + VarHelper.Instance.DownDir;
    
                    UpdateHelper.Instance.DownloadDir(VarHelper.Instance.DownDir + ".zip", VarHelper.Instance.InitPath);//需要下载的压缩文件名称
                    //从那解压到哪
                    SharpZip.UnpackFiles(fileZip + ".zip", target);//MessageBox.Show("解压target==" + target);  //ClassZip.UnZip(fileZip + ".zip", target);
                    DialogResult result = MessageBox.Show("更新已完成,是否启动预约程序?", "提示",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (result.Equals(DialogResult.OK))
                    {
                        File.Delete(fileZip + ".zip");//MessageBox.Show("开始删除临时压缩文件" + fileZip + ".zip");
    
                        string mainExe = VarHelper.Instance.InitPath + VarHelper.Instance.MainExe;//"\QueueSys";
                        ProcessHelper.Instance.StartProcessByName(mainExe);                    //MessageBox.Show("启动==" + mainExe);
                        ProcessHelper.Instance.KillProcessByName("AutoUpdate");
                        //System.GC.Collect();//垃圾回收
                    }
    
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("删除压缩文件==" + ex.Message + ex.StackTrace);
                    MessageBox.Show("更新失败,请联系管理员");
                    LogHelper.Instance.SaveText("" + ex.Message + ex.StackTrace);
                    return;
                }
            }
    
            private void NewMethod()
            {
                // 第一步下载需要更新的配置文件
                string filepath = "UpdateList.xml";
                UpdateHelper.Instance.Download(filepath);
                // 第二步 提供并解析配置文件(获取需要更新的文件名称、文件更新后的路径)
                string path = Application.StartupPath + "\UpdateList.xml";
                List<UpdateList> list = AutoUpdate.Helper.XmlHelper.Instance.GetUpdateList(path, "Root");
                //第三步 循环下载文件到指定路径
                foreach (UpdateList item in list)
                {
                    if (string.IsNullOrEmpty(item.PATH)) UpdateHelper.Instance.Download(item.NAME);//下载至根目录
                    else //下载至指定目录
                    {
                        string targetPath = Application.StartupPath + "\" + item.PATH + "\" + item.NAME;
                        UpdateHelper.Instance.Download(item.NAME, targetPath);
                    }
                }
            }
    
            private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
            {
                DialogResult result = MessageBox.Show("程序正在更新,退出将导致异常", "是否确认退出",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result.Equals(DialogResult.OK))
                {
                    Application.Exit();
                }
            }
    
            private void buttonTest_Click(object sender, EventArgs e)
            {
                UpdateApp();
            }
    
    
        }
    }

     
    主程序:

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace AutoUpdateApp
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                DirectoryInfo info = new DirectoryInfo(Application.StartupPath);
                string path = info.Parent.Parent.FullName;
    
                DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}....", Application.StartupPath));
                string fullPath = di.FullName;
    
                //初始路径 + 自动更新程序名称 + 主程序名称 
                string param = fullPath + "," 
                    + "AutoUpdate\AutoUpdate.exe," //自动更新程序
                    + "Debug\AutoUpdateApp.exe,"//主程序
                    + "Debug";//下载包
    
                //AutoUpdate
                Process p = new Process();//声明一个进程类对象
                p.StartInfo.FileName = fullPath + "AutoUpdate\AutoUpdate.exe";
                p.StartInfo.UseShellExecute = true;
                p.StartInfo.Arguments = param;//第一个参数为需要下载的压缩文件,第二个为需要启动的程序
                p.Start();
    
                //关闭当期
                //Process[] p_arry = Process.GetProcesses();//得到系统所有进程
                //for (int i = 0; i < p_arry.Length; i++)//遍历每个进程
                //{
                //    if (p_arry[i].ProcessName == "AutoUpdateApp")//发现有名为QQ的进程
                //    {
                //        p_arry[i].Kill();//就结束它。
                //        return;
                //    }
                //}
              
                KillProcessByName("AutoUpdateApp");
                System.GC.Collect();//垃圾回收
            }
    
            /// <summary>
            /// 关闭进程
            /// </summary>
            /// <param name="processName">进程名</param>
            public void KillProcessByName(string processName)
            {
                try
                {
                    Process[] myproc = Process.GetProcesses();
                    foreach (Process item in myproc)
                    {
                        if (item.ProcessName == processName)
                        {
                            item.CloseMainWindow();
                            item.Kill();
                        }
                    }
                }
                catch { return; }
            }
    
        }
    }
    

      

    博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!
  • 相关阅读:
    正则表达式入门教程
    js获取class
    锋利的jQuery第6章 jQuery与Ajax的应用
    显示隐藏左侧菜单
    unicode转为汉字
    $.ajax
    .ashx文件
    c#正则表达式
    调试发现的小错误
    sql2005连接不到本地数据库
  • 原文地址:https://www.cnblogs.com/YYkun/p/14446630.html
Copyright © 2020-2023  润新知