主頁 > .NET開發 > C# WinForm通用自動更新器

C# WinForm通用自動更新器

2021-10-11 06:57:41 .NET開發

一、引言

對于C/S架構來說,軟體更新是一個很常用的功能,下面介紹一種非常實用的軟體自動升級方案,

二、示意圖

三、專案說明

3.1、專案創建

新建4個專案,如下所示:

3.2、專案關系

四、LinkTo.Toolkit

LinkTo.Toolkit主要是一些Utility及Helper類檔案,實作轉換擴展、檔案讀寫、行程處理等功能,

    /// <summary>
    /// 轉換擴展類
    /// </summary>
    public static class ConvertExtension
    {
        public static string ToString2(this object obj)
        {
            if (obj == null)
                return string.Empty;
            return obj.ToString();
        }

        public static DateTime? ToDateTime(this string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            if (DateTime.TryParse(str, out DateTime dateTime))
            {
                return dateTime;
            }
            return null;
        }

        public static bool ToBoolean(this string str)
        {
            if (string.IsNullOrEmpty(str)) return false;
            return str.ToLower() == bool.TrueString.ToLower();
        }

        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        public static int ToInt(this string str)
        {
            if (int.TryParse(str, out int intValue))
            {
                return intValue;
            }
            return 0;
        }

        public static long ToLong(this string str)
        {
            if (long.TryParse(str, out long longValue))
            {
                return longValue;
            }
            return 0;
        }

        public static decimal ToDecimal(this string str)
        {
            if (decimal.TryParse(str, out decimal decimalValue))
            {
                return decimalValue;
            }
            return 0;
        }

        public static double ToDouble(this string str)
        {
            if (double.TryParse(str, out double doubleValue))
            {
                return doubleValue;
            }
            return 0;
        }

        public static float ToFloat(this string str)
        {
            if (float.TryParse(str, out float floatValue))
            {
                return floatValue;
            }
            return 0;
        }

        /// <summary>
        /// DataRow轉換為物體類
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ConvertToEntityByDataRow<T>(this DataRow dataRow) where T : new()
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            T t = new T();
            if (dataRow == null) return t;
            foreach (PropertyInfo property in properties)
            {
                foreach (DataColumn column in dataRow.Table.Columns)
                {
                    if (property.Name.Equals(column.ColumnName, StringComparison.OrdinalIgnoreCase))
                    {
                        object value =https://www.cnblogs.com/atomy/p/ dataRow[column];
                        if (value != null && value != DBNull.Value)
                        {
                            if (value.GetType().Name != property.PropertyType.Name)
                            {
                                if (property.PropertyType.IsEnum)
                                {
                                    property.SetValue(t, Enum.Parse(property.PropertyType, value.ToString()), null);
                                }
                                else
                                {
                                    try
                                    {
                                        value = Convert.ChangeType(value, (Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType));
                                        property.SetValue(t, value, null);
                                    }
                                    catch { }
                                }
                            }
                            else
                            {
                                property.SetValue(t, value, null);
                            }
                        }
                        else
                        {
                            property.SetValue(t, null, null);
                        }
                        break;
                    }
                }
            }
            return t;
        }

        /// <summary>
        /// 通用簡單物體型別互轉
        /// </summary>
        public static T ConvertToEntity<T>(this object sourceEntity) where T : new()
        {
            T t = new T();
            Type sourceType = sourceEntity.GetType();
            if (sourceType.Equals(typeof(DataRow)))
            {
                //DataRow型別
                DataRow dataRow = sourceEntity as DataRow;
                t = dataRow.ConvertToEntityByDataRow<T>();
            }
            else
            {
                Type type = typeof(T);
                PropertyInfo[] properties = type.GetProperties();
                PropertyInfo[] sourceProperties = sourceType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    foreach (var sourceProperty in sourceProperties)
                    {
                        if (sourceProperty.Name.Equals(property.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            object value = https://www.cnblogs.com/atomy/p/sourceProperty.GetValue(sourceEntity, null);
                            if (value != null && value != DBNull.Value)
                            {
                                if (sourceProperty.PropertyType.Name != property.PropertyType.Name)
                                {
                                    if (property.PropertyType.IsEnum)
                                    {
                                        property.SetValue(t, Enum.Parse(property.PropertyType, value.ToString()), null);
                                    }
                                    else
                                    {
                                        try
                                        {
                                            value = Convert.ChangeType(value, (Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType));
                                            property.SetValue(t, value, null);
                                        }
                                        catch { }
                                    }
                                }
                                else
                                {
                                    property.SetValue(t, value, null);
                                }
                            }
                            else
                            {
                                property.SetValue(t, null, null);
                            }
                            break;
                        }
                    }
                }
            }
            return t;
        }

        /// <summary>
        /// 通用簡單物體型別互轉
        /// </summary>
        public static List<T> ConvertToEntityList<T>(this object list) where T : new()
        {
            List<T> t = new List<T>();
            if (list == null) return t;
            Type sourceObj = list.GetType();
            if (sourceObj.Equals(typeof(DataTable)))
            {
                var dataTable = list as DataTable;
                t = dataTable.Rows.Cast<DataRow>().Where(m => !(m.RowState == DataRowState.Deleted || m.RowState == DataRowState.Detached)).Select(m => m.ConvertToEntityByDataRow<T>()).ToList();
            }
            else if (list is IEnumerable)
            {
                t = ((IList)list).Cast<object>().Select(m => m.ConvertToEntity<T>()).ToList();
            }
            return t;
        }

        /// <summary>
        /// 轉換為DataTable,如果是集合沒有資料行的時候會拋例外,
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ConvertToDataTable(this object list)
        {
            if (list == null) return null;
            DataTable dataTable = new DataTable();
            if (list is IEnumerable)
            {
                var li = (IList)list;
                //li[0]代表的是一個物件,list沒有行時,會拋例外,
                PropertyInfo[] properties = li[0].GetType().GetProperties();
                dataTable.Columns.AddRange(properties.Where(m => !m.PropertyType.IsClass || !m.PropertyType.IsInterface).Select(m =>
                    new DataColumn(m.Name, Nullable.GetUnderlyingType(m.PropertyType) ?? m.PropertyType)).ToArray());
                foreach (var item in li)
                {
                    DataRow dataRow = dataTable.NewRow();
                    foreach (PropertyInfo property in properties.Where(m => m.PropertyType.GetProperty("Item") == null))    //過濾含有索引器的屬性
                    {
                        object value = https://www.cnblogs.com/atomy/p/property.GetValue(item, null);
                        dataRow[property.Name] = value ?? DBNull.Value;
                    }
                    dataTable.Rows.Add(dataRow);
                }
            }
            else
            {
                PropertyInfo[] properties = list.GetType().GetProperties();
                properties = properties.Where(m => m.PropertyType.GetProperty("Item") == null).ToArray();   //過濾含有索引器的屬性
                dataTable.Columns.AddRange(properties.Select(m => new DataColumn(m.Name, Nullable.GetUnderlyingType(m.PropertyType) ?? m.PropertyType)).ToArray());
                DataRow dataRow = dataTable.NewRow();
                foreach (PropertyInfo property in properties)
                {
                    object value = https://www.cnblogs.com/atomy/p/property.GetValue(list, null);
                    dataRow[property.Name] = value ?? DBNull.Value;
                }
                dataTable.Rows.Add(dataRow);
            }
            return dataTable;
        }

        /// <summary>
        /// 物體類公共屬性值復制
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="target"></param>
        public static void CopyTo(this object entity, object target)
        {
            if (target == null) return;
            if (entity.GetType() != target.GetType())
                return;
            PropertyInfo[] properties = target.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType.GetProperty("Item") != null)
                    continue;
                object value = https://www.cnblogs.com/atomy/p/property.GetValue(entity, null);
                if (value != null)
                {
                    if (value is ICloneable)
                    {
                        property.SetValue(target, (value as ICloneable).Clone(), null);
                    }
                    else
                    {
                        property.SetValue(target, value.Copy(), null);
                    }
                }
                else
                {
                    property.SetValue(target, null, null);
                }
            }
        }

        public static object Copy(this object obj)
        {
            if (obj == null) return null;
            object targetDeepCopyObj;
            Type targetType = obj.GetType();
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            else
            {
                targetDeepCopyObj = Activator.CreateInstance(targetType);   //創建參考物件
                MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (MemberInfo member in memberCollection)
                {
                    if (member.GetType().GetProperty("Item") != null)
                        continue;
                    if (member.MemberType == MemberTypes.Field)
                    {
                        FieldInfo field = (FieldInfo)member;
                        object fieldValue =https://www.cnblogs.com/atomy/p/ field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, fieldValue.Copy());
                        }
                    }
                    else if (member.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo property = (PropertyInfo)member;
                        MethodInfo method = property.GetSetMethod(false);
                        if (method != null)
                        {
                            object propertyValue = https://www.cnblogs.com/atomy/p/property.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                property.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                property.SetValue(targetDeepCopyObj, propertyValue.Copy(), null);
                            }
                        }
                    }
                }
            }
            return targetDeepCopyObj;
        }
    }
ConvertExtension.cs
    public class FileHelper
    {
        private readonly string strUpdateFilesPath;

        public FileHelper(string strDirector)
        {
            strUpdateFilesPath = strDirector;
        }

        //保存所有的檔案資訊
        private List<FileInfo> listFiles = new List<FileInfo>();

        public List<FileInfo> GetAllFilesInDirectory(string strDirector)
        {
            DirectoryInfo directory = new DirectoryInfo(strDirector);
            DirectoryInfo[] directoryArray = directory.GetDirectories();
            FileInfo[] fileInfoArray = directory.GetFiles();
            if (fileInfoArray.Length > 0) listFiles.AddRange(fileInfoArray);

            foreach (DirectoryInfo item in directoryArray)
            {
                DirectoryInfo directoryA = new DirectoryInfo(item.FullName);
                DirectoryInfo[] directoryArrayA = directoryA.GetDirectories();
                GetAllFilesInDirectory(item.FullName);
            }
            return listFiles;
        }

        public string[] GetUpdateList(List<FileInfo> listFileInfo)
        {
            var fileArrary = listFileInfo.Cast<FileInfo>().Select(s => s.FullName.Replace(strUpdateFilesPath, "")).ToArray();
            return fileArrary;
        }

        /// <summary>
        /// 洗掉檔案夾下的所有檔案但不洗掉目錄
        /// </summary>
        /// <param name="dirRoot"></param>
        public static void DeleteDirAllFile(string dirRoot)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(dirRoot));
            FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
            foreach (FileInfo item in files)
            {
                File.Delete(item.FullName);
            }
        }
    }
FileHelper.cs
    public static class FileUtility
    {
        #region 讀取檔案
        /// <summary>
        /// 讀取檔案
        /// </summary>
        /// <param name="filePath">檔案路徑</param>
        /// <returns></returns>
        public static string ReadFile(string filePath)
        {
            string result = string.Empty;

            if (File.Exists(filePath) == false)
            {
                return result;
            }

            try
            {
                using (var streamReader = new StreamReader(filePath, Encoding.UTF8))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (Exception)
            {
                result = string.Empty;
            }

            return result;
        }

        #endregion 讀檔案

        #region 寫入檔案
        /// <summary>
        /// 寫入檔案
        /// </summary>
        /// <param name="filePath">檔案路徑</param>
        /// <param name="strValue">寫入內容</param>
        /// <returns></returns>
        public static bool WriteFile(string filePath, string strValue)
        {
            try
            {
                if (File.Exists(filePath) == false)
                {
                    using (FileStream fileStream = File.Create(filePath)) { }
                }

                using (var streamWriter = new StreamWriter(filePath, true, Encoding.UTF8))
                {
                    streamWriter.WriteLine(strValue);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region 洗掉檔案
        /// <summary>
        /// 洗掉檔案
        /// </summary>
        /// <param name="filePath">檔案路徑</param>
        /// <returns></returns>
        public static bool DeleteFile(string filePath)
        {
            try
            {
                File.Delete(filePath);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion 洗掉檔案

        #region 為檔案添加用戶組的完全控制權限
        /// <summary>
        /// 為檔案添加用戶組的完全控制權限
        /// </summary>
        /// <param name="userGroup">用戶組</param>
        /// <param name="filePath">檔案路徑</param>
        /// <returns></returns>
        public static bool AddSecurityControll2File(string userGroup, string filePath)
        {
            try
            {
                //獲取檔案資訊
                FileInfo fileInfo = new FileInfo(filePath);
                //獲得該檔案的訪問權限
                FileSecurity fileSecurity = fileInfo.GetAccessControl();
                //添加用戶組的訪問權限規則--完全控制權限
                fileSecurity.AddAccessRule(new FileSystemAccessRule(userGroup, FileSystemRights.FullControl, AccessControlType.Allow));
                //設定訪問權限
                fileInfo.SetAccessControl(fileSecurity);
                //回傳結果
                return true;
            }
            catch (Exception)
            {
                //回傳結果
                return false;
            }
        }
        #endregion

        #region 為檔案夾添加用戶組的完全控制權限
        /// <summary>
        /// 為檔案夾添加用戶組的完全控制權限
        /// </summary>
        /// <param name="userGroup">用戶組</param>
        /// <param name="dirPath">檔案夾路徑</param>
        /// <returns></returns>
        public static bool AddSecurityControll2Folder(string userGroup,string dirPath)
        {
            try
            {
                //獲取檔案夾資訊
                DirectoryInfo dir = new DirectoryInfo(dirPath);
                //獲得該檔案夾的所有訪問權限
                DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
                //設定檔案ACL繼承
                InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
                //添加用戶組的訪問權限規則--完全控制權限
                FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule(userGroup, FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out bool isModified);
                //設定訪問權限
                dir.SetAccessControl(dirSecurity);
                //回傳結果
                return true;
            }
            catch (Exception)
            {
                //回傳結果
                return false;
            }
        }
        #endregion
    }
FileUtility.cs
    public static class ProcessUtility
    {
        #region 關閉行程
        /// <summary>
        /// 關閉行程
        /// </summary>
        /// <param name="processName">行程名</param>
        public static void KillProcess(string processName)
        {
            Process[] myproc = Process.GetProcesses();
            foreach (Process item in myproc)
            {
                if (item.ProcessName == processName)
                {
                    item.Kill();
                }
            }
        }
        #endregion
    }
ProcessUtility.cs
    /// <summary>
    /// Xml序列化與反序列化
    /// </summary>
    public static class XmlUtility
    {
        #region 序列化

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">型別</param>
        /// <param name="obj">物件</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化物件
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

        #endregion 序列化

        #region 反序列化

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">型別</param>
        /// <param name="xml">XML字串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            return xmldes.Deserialize(stream);
        }

        #endregion 反序列化
    }
XmlUtility.cs

五、AutoUpdaterTest

5.1、物體類

作用:本地配置AutoUpdateConfig.xml檔案的序列化及反序列化物體物件,

    public class AutoUpdateConfig
    {
        /// <summary>
        /// 自動升級模式:當前僅支持HTTP
        /// </summary>
        public string AutoUpdateMode { get; set; }

        /// <summary>
        /// HTTP自動升級模式時的URL地址
        /// </summary>
        public string AutoUpdateHttpUrl { get; set; }
    }
AutoUpdateConfig.cs

5.2、通用類

作用:應用程式全域靜態常量,全域引數都在此設定,方便統一管理,注:客戶端是否檢測更新,也是在此設定默認值,

    /// <summary>
    /// 應用程式全域靜態常量
    /// </summary>
    public static class GlobalParam
    {
        #region 自動更新引數
        /// <summary>
        /// 是否檢查自動更新:默認是true
        /// </summary>
        public static string CheckAutoUpdate = "true";

        /// <summary>
        /// 本地自動更新配置XML檔案名
        /// </summary>
        public const string AutoUpdateConfig_XmlFileName = "AutoUpdateConfig.xml";

        /// <summary>
        /// 本地自動更新下載臨時存放目錄
        /// </summary>
        public const string TempDir = "Temp";

        /// <summary>
        /// 遠端自動更新資訊XML檔案名
        /// </summary>
        public const string AutoUpdateInfo_XmlFileName = "AutoUpdateInfo.xml";

        /// <summary>
        /// 遠端自動更新檔案存放目錄
        /// </summary>
        public const string RemoteDir = "AutoUpdateFiles";

        /// <summary>
        /// 主執行緒名
        /// </summary>
        public const string MainProcess = "AutoUpdaterTest";
        #endregion
    }
GlobalParam.cs

作用:應用程式背景關系,

    /// <summary>
    /// 應用程式背景關系
    /// </summary>
    public class AppContext
    {
        /// <summary>
        /// 客戶端組態檔
        /// </summary>
        public static AutoUpdateConfig AutoUpdateConfigData { get; set; }
    }
AppContext.cs

作用:應用程式配置,

    public class AppConfig
    {
        private static readonly object _lock = new object();
        private static AppConfig _instance = null;

        #region 自動更新配置
        /// <summary>
        /// 自動更新配置資料
        /// </summary>
        public AutoUpdateConfig AutoUpdateConfigData { get; set; }

        private AppConfig()
        {
            AutoUpdateConfigData = new AutoUpdateConfig();
        }

        public static AppConfig Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new AppConfig();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 本地自動更新下載臨時檔案夾路徑
        /// </summary>
        public string TempPath
        {
            get
            {
                return string.Format("{0}\\{1}", Application.StartupPath, GlobalParam.TempDir);
            }
        }

        /// <summary>
        /// 初始化系統配置資訊
        /// </summary>
        public void InitialSystemConfig()
        {
            AutoUpdateConfigData.AutoUpdateMode = AppContext.AutoUpdateConfigData.AutoUpdateMode;
            AutoUpdateConfigData.AutoUpdateHttpUrl = AppContext.AutoUpdateConfigData.AutoUpdateHttpUrl;
        }
        #endregion
    }
AppConfig.cs

5.3、工具類

作用:組態檔的讀寫,

    public class AutoUpdateHelper
    {
        private readonly string AutoUpdateMode = string.Empty;

        public AutoUpdateHelper(string autoUpdateMode)
        {
            AutoUpdateMode = autoUpdateMode;
        }

        /// <summary>
        /// 加載本地自動更新組態檔
        /// </summary>
        /// <returns></returns>
        public static AutoUpdateConfig Load()
        {
            string filePath = string.Empty, fileContent = string.Empty;
            filePath = Path.Combine(Application.StartupPath, GlobalParam.AutoUpdateConfig_XmlFileName);
            AutoUpdateConfig config = new AutoUpdateConfig();
            fileContent = FileUtility.ReadFile(filePath);
            object obj = XmlUtility.Deserialize(typeof(AutoUpdateConfig), fileContent);
            config = obj as AutoUpdateConfig;
            return config;
        }

        /// <summary>
        /// 獲取遠端自動更新資訊的版本號
        /// </summary>
        /// <returns></returns>
        public string GetRemoteAutoUpdateInfoVersion()
        {
            XDocument doc = new XDocument();
            doc = XDocument.Parse(GetRemoteAutoUpdateInfoXml());
            return doc.Element("AutoUpdateInfo").Element("NewVersion").Value;
        }

        /// <summary>
        /// 獲取遠端自動更新資訊的XML檔案內容
        /// </summary>
        /// <returns></returns>
        public string GetRemoteAutoUpdateInfoXml()
        {
            string remoteXmlAddress = AppConfig.Instance.AutoUpdateConfigData.AutoUpdateHttpUrl + "/" + GlobalParam.AutoUpdateInfo_XmlFileName;
            string receiveXmlPath = Path.Combine(AppConfig.Instance.TempPath, GlobalParam.AutoUpdateInfo_XmlFileName);
            string xmlString = string.Empty;

            if (Directory.Exists(AppConfig.Instance.TempPath) == false)
            {
                Directory.CreateDirectory(AppConfig.Instance.TempPath);
            }

            if (AutoUpdateMode.ToUpper() == "HTTP")
            {
                WebClient client = new WebClient();
                client.DownloadFile(remoteXmlAddress, receiveXmlPath);
            }

            if (File.Exists(receiveXmlPath))
            {
                xmlString = FileUtility.ReadFile(receiveXmlPath);
                return xmlString;
            }

            return string.Empty;
        }

        /// <summary>
        /// 寫入本地自動更新配置的XML檔案內容
        /// </summary>
        /// <returns></returns>
        public string WriteLocalAutoUpdateInfoXml()
        {
            string xmlPath = string.Empty, xmlValue = https://www.cnblogs.com/atomy/p/string.Empty;

            xmlPath = Path.Combine(AppConfig.Instance.TempPath, GlobalParam.AutoUpdateConfig_XmlFileName);
            xmlValue = XmlUtility.Serializer(typeof(AutoUpdateConfig), AppConfig.Instance.AutoUpdateConfigData);

            if (File.Exists(xmlPath))
            {
                File.Delete(xmlPath);
            }

            bool blSuccess = FileUtility.WriteFile(xmlPath, xmlValue);
            return blSuccess == true ? xmlPath : "";
        }
    }
AutoUpdateHelper.cs

5.4、本地組態檔

作用:配置自動更新模式及相關,

注1:復制到輸出目錄選擇始終復制,

注2:主程式運行時,先讀取此配置更新檔案,然后給AppContext背景關系賦值,接著給AppConfig配置賦值,

<?xml version="1.0" encoding="utf-8" ?>
<AutoUpdateConfig>
  <!--自動升級模式:當前僅支持HTTP-->
  <AutoUpdateMode>HTTP</AutoUpdateMode>
  <!--HTTP自動升級模式時的URL地址-->
  <AutoUpdateHttpUrl>http://127.0.0.1:6600/AutoUpdateDir</AutoUpdateHttpUrl>
</AutoUpdateConfig>
AutoUpdateConfig.xml

5.5、主程式

新建一個Windows 表單MainForm,此處理僅需要一個空白表單即可,作測驗用,

    public partial class MainForm : Form
    {
        private static MainForm _Instance;

        /// <summary>
        /// MainForm主表單實體
        /// </summary>
        public static MainForm Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new MainForm();
                }
                return _Instance;
            }
        }

        public MainForm()
        {
            InitializeComponent();
        }
    }
MainForm.cs

5.6、應用程式主入口

作用:檢測應用程式是否需要自動更新,如里需要則檢測遠程服務端的版本號,假如遠程服務端有新版本,則呼叫自動更新器AutoUpdater并向其傳遞4個引數,

    internal static class Program
    {
        /// <summary>
        /// 應用程式的主入口點
        /// </summary>
        [STAThread]
        private static void Main(string[] args)
        {
            //嘗試設定訪問權限
            FileUtility.AddSecurityControll2Folder("Users", Application.StartupPath);

            //未捕獲的例外處理
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //是否檢查自動更新賦值
            if (args.Length > 0)
            {
                GlobalParam.CheckAutoUpdate = args[0];
            }

            //加載自動更新組態檔,給背景關系AppServiceConfig物件賦值,
            var config = AutoUpdateHelper.Load();
            AppContext.AutoUpdateConfigData = config;

            //表單互斥體
            var instance = new Mutex(true, GlobalParam.MainProcess, out bool isNewInstance);
            if (isNewInstance == true)
            {
                if (GlobalParam.CheckAutoUpdate.ToBoolean())
                {
                    if (CheckUpdater())
                        ProcessUtility.KillProcess(GlobalParam.MainProcess);
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(MainForm.Instance);
                instance.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("已經啟動了一個程式,請先退出,", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }

        /// <summary>
        /// 自動更新檢測
        /// </summary>
        /// <returns></returns>
        private static bool CheckUpdater()
        {
            if (GlobalParam.CheckAutoUpdate.ToBoolean() == false) return false;

            #region 檢查版本更新
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            bool blFinish = false;
            AppConfig.Instance.InitialSystemConfig();
            var helper = new AutoUpdateHelper(AppConfig.Instance.AutoUpdateConfigData.AutoUpdateMode);
            string fileVersion = FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion;

            long localVersion = 0;
            long remoteVersion = 0;
            try
            {
                localVersion = fileVersion.Replace(".", "").ToLong();
                remoteVersion = helper.GetRemoteAutoUpdateInfoVersion().Replace(".", "").ToLong();

                if ((localVersion > 0) && (localVersion < remoteVersion))
                {
                    blFinish = true;
                    string autoUpdateConfigXmlPath = helper.WriteLocalAutoUpdateInfoXml();
                    string autoUpdateInfoXmlPath = Path.Combine(AppConfig.Instance.TempPath, GlobalParam.AutoUpdateInfo_XmlFileName);
                    string argument1 = autoUpdateConfigXmlPath;
                    string argument2 = autoUpdateInfoXmlPath;
                    string argument3 = GlobalParam.MainProcess;
                    string argument4 = GlobalParam.RemoteDir;
                    string arguments = argument1 + " " + argument2 + " " + argument3 + " " + argument4;
                    Process.Start("AutoUpdater.exe", arguments);
                    Application.Exit();
                }
            }
            catch (TimeoutException)
            {
                blFinish = false;
            }
            catch (WebException)
            {
                blFinish = false;
            }
            catch (Exception)
            {
                blFinish = false;
            }
            
            return blFinish;
            #endregion
        }

        /// <summary>
        /// UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";
            var error = e.Exception;

            if (error != null)
            {
                strError = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}\r\n來源資訊:{error.Source}\r\n";
            }
            else
            {
                strError = $"Application ThreadException:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 非UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";

            if (e.ExceptionObject is Exception error)
            {
                strError = strDateInfo + $"例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}";
            }
            else
            {
                strError = $"Application UnhandledError:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 寫入日志
        /// </summary>
        /// <param name="strLog"></param>
        private static void WriteLog(string strLog)
        {
            string dirPath = @"Log\MainProcess", fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            string strLine = "----------------------------------------------------------------------------------------------------";

            FileUtility.WriteFile(Path.Combine(dirPath, fileName), strLog);
            FileUtility.WriteFile(Path.Combine(dirPath,fileName), strLine);
        }
    }
Program.cs

六、AutoUpdater

6.1、物體類

作用:配置自動更新模式及相關,

    /// <summary>
    /// 自動更新配置資訊
    /// </summary>
    public class AutoUpdateConfig
    {
        /// <summary>
        /// 自動升級模式:當前僅支持HTTP
        /// </summary>
        public string AutoUpdateMode { get; set; }

        /// <summary>
        /// HTTP自動升級模式時的URL地址
        /// </summary>
        public string AutoUpdateHttpUrl { get; set; }
    }
AutoUpdateConfig.cs

作用:自動更新內容資訊,

    /// <summary>
    /// 自動更新內容資訊
    /// </summary>
    [Serializable]
    public class AutoUpdateInfo
    {
        /// <summary>
        /// 新版本號
        /// </summary>
        public string NewVersion { get; set; }

        /// <summary>
        /// 更新日期
        /// </summary>
        public string UpdateTime { get; set; }

        /// <summary>
        /// 更新內容說明
        /// </summary>
        public string UpdateContent { get; set; }

        /// <summary>
        /// 更新檔案串列
        /// </summary>
        public List<string> FileList { get; set; }
    }
AutoUpdateInfo.cs

6.2、通用類

作用:應用程式全域靜態常量,全域引數都在此設定,方便統一管理,

    /// <summary>
    /// 應用程式全域靜態常量
    /// </summary>
    public static class GlobalParam
    {
        /// <summary>
        /// 呼叫程式主執行緒名稱
        /// </summary>
        public static string MainProcess = string.Empty;

        /// <summary>
        /// 遠程更新程式所在檔案夾的名稱
        /// </summary>
        public static string RemoteDir = string.Empty;
    }
GlobalParam.cs

6.3、Window 表單

新建一個Windows 表單HttpStartUp,

    public partial class HttpStartUp : Form
    {
        private bool _blSuccess = false;
        private string _autoUpdateHttpUrl = null;
        private AutoUpdateInfo _autoUpdateInfo = null;

        public HttpStartUp(string autoUpdateHttpUrl, AutoUpdateInfo autoUpdateInfo)
        {
            InitializeComponent();
            _autoUpdateHttpUrl = autoUpdateHttpUrl;
            _autoUpdateInfo = autoUpdateInfo;
            _blSuccess = false;
        }

        /// <summary>
        /// 表單加載事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_Load(object sender, EventArgs e)
        {
            Text = GlobalParam.MainProcess + "-更新程式";
            lblUpdateTime.Text = _autoUpdateInfo.UpdateTime;
            lblNewVersion.Text = _autoUpdateInfo.NewVersion;
            txtUpdate.Text = _autoUpdateInfo.UpdateContent;
        }

        /// <summary>
        /// 立即更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRun_Click(object sender, EventArgs e)
        {
            ProcessUtility.KillProcess(GlobalParam.MainProcess);
            btnRun.Enabled = false;
            btnLeave.Enabled = false;
            
            Thread thread = new Thread(() =>
            {
                try
                {
                    var downFileList = _autoUpdateInfo.FileList.OrderByDescending(s => s.IndexOf("\\"));
                    foreach (var fileName in downFileList)
                    {
                        string fileUrl = string.Empty, fileVaildPath = string.Empty;
                        if (fileName.StartsWith("\\"))
                        {
                            fileVaildPath = fileName.Substring(fileName.IndexOf("\\"));
                        }
                        else
                        {
                            fileVaildPath = fileName;
                        }
                        fileUrl = _autoUpdateHttpUrl.TrimEnd(new char[] { '/' }) + @"/" + GlobalParam.RemoteDir + @"/" + fileVaildPath.Replace("\\", "/");    //替換檔案目錄中的路徑為網路路徑
                        DownloadFileDetail(fileUrl, fileName);
                    }
                    _blSuccess = true;
                }
                catch (Exception ex)
                {
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        throw ex;
                    }));
                }
                finally
                {
                    BeginInvoke(new MethodInvoker(delegate ()
                    {
                        btnRun.Enabled = true;
                        btnLeave.Enabled = true;
                    }));
                }
                if (_blSuccess)
                {
                    Process.Start(GlobalParam.MainProcess + ".exe");
                    BeginInvoke(new MethodInvoker(delegate ()
                    {
                        Close();
                        Application.Exit();
                    }));
                }
            })
            {
                IsBackground = true
            };
            thread.Start();
        }

        private void DownloadFileDetail(string httpUrl, string filename)
        {
            string fileName = Application.StartupPath + "\\" + filename;
            string dirPath = GetDirPath(fileName);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream httpStream = response.GetResponseStream();
            long totalBytes = response.ContentLength;
            if (progressBar != null)
            {
                BeginInvoke(new MethodInvoker(delegate ()
                {
                    lblDownInfo.Text = "開始下載...";
                    progressBar.Maximum = (int)totalBytes;
                    progressBar.Minimum = 0;
                }));
            }
            FileStream outputStream = new FileStream(fileName, FileMode.Create);
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = httpStream.Read(buffer, 0, bufferSize);
            int allByte = (int)response.ContentLength;
            int startByte = 0;
            BeginInvoke(new MethodInvoker(delegate ()
            {
                progressBar.Maximum = allByte;
                progressBar.Minimum = 0;
            }));
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = httpStream.Read(buffer, 0, bufferSize);
                startByte += readCount;
                BeginInvoke(new MethodInvoker(delegate ()
                {
                    lblDownInfo.Text = "已下載:" + startByte / 1024 + "KB/" + "總長度:"+ allByte / 1024 + "KB" + " " + " 檔案名:" + filename;         
                    progressBar.Value = startByte;
                }));
                Application.DoEvents();
                Thread.Sleep(5);
            }
            BeginInvoke(new MethodInvoker(delegate ()
            {
                lblDownInfo.Text = "下載完成,";
            }));
            httpStream.Close();
            outputStream.Close();
            response.Close();
        }

        public static string GetDirPath(string filePath)
        {
            if (filePath.LastIndexOf("\\") > 0)
            {
                return filePath.Substring(0, filePath.LastIndexOf("\\"));
            }
            return filePath;
        }

        /// <summary>
        /// 暫不更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLeave_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("確定要放棄此次更新嗎?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Process.Start(GlobalParam.MainProcess + ".exe", "false");
                Close();
                Application.Exit();
            }
        }      
    }
HttpStartUp.cs

6.4、應用程式主入口

    internal static class Program
    {
        /// <summary>
        /// 應用程式的主入口點
        /// </summary>
        [STAThread]
        private static void Main(string[] args)
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #region 測驗
            //string strArgs = @"E:\LinkTo.AutoUpdater\AutoUpdaterTest\bin\Debug\Temp\AutoUpdateConfig.xml"+" "+@"E:\LinkTo.AutoUpdater\AutoUpdaterTest\bin\Debug\Temp\AutoUpdateInfo.xml"+" "+"AutoUpdaterTest"+" "+"AutoUpdateFiles";
            //args = strArgs.Split(' ');
            #endregion

            if (args.Length > 0)
            {
                string autoUpdateConfigXmlPath = args[0].ToString();
                string autoUpdateInfoXmlPath = args[1].ToString();
                GlobalParam.MainProcess = args[2].ToString();
                GlobalParam.RemoteDir = args[3].ToString();

                var autoUpdateConfigXml = FileUtility.ReadFile(autoUpdateConfigXmlPath);
                var autoUpdateInfoXml = FileUtility.ReadFile(autoUpdateInfoXmlPath);
                AutoUpdateConfig config = XmlUtility.Deserialize(typeof(AutoUpdateConfig), autoUpdateConfigXml) as AutoUpdateConfig;
                AutoUpdateInfo info = XmlUtility.Deserialize(typeof(AutoUpdateInfo), autoUpdateInfoXml) as AutoUpdateInfo;

                if (config.AutoUpdateMode.ToUpper() == "HTTP")
                {
                    Application.Run(new HttpStartUp(config.AutoUpdateHttpUrl, info));
                }
            }
            else
            {
                Application.Exit();
            }
        }

        /// <summary>
        /// UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";
            var error = e.Exception;

            if (error != null)
            {
                strError = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}\r\n來源資訊:{error.Source}\r\n";
            }
            else
            {
                strError = $"Application ThreadException:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 非UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";

            if (e.ExceptionObject is Exception error)
            {
                strError = strDateInfo + $"例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}";
            }
            else
            {
                strError = $"Application UnhandledError:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 寫入日志
        /// </summary>
        /// <param name="strLog"></param>
        private static void WriteLog(string strLog)
        {
            string dirPath = @"Log\AutoUpdater", fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            string strLine = "----------------------------------------------------------------------------------------------------";

            FileUtility.WriteFile(Path.Combine(dirPath, fileName), strLog);
            FileUtility.WriteFile(Path.Combine(dirPath, fileName), strLine);
        }
    }
Program.cs

七、AutoUpdateXmlBuilder

7.1、物體類

作用:自動更新內容資訊,

    /// <summary>
    /// 自動更新內容資訊
    /// </summary>
    [Serializable]
    public class AutoUpdateInfo
    {
        /// <summary>
        /// 新版本號
        /// </summary>
        public string NewVersion { get; set; }

        /// <summary>
        /// 更新日期
        /// </summary>
        public string UpdateTime { get; set; }

        /// <summary>
        /// 更新內容說明
        /// </summary>
        public string UpdateContent { get; set; }

        /// <summary>
        /// 更新檔案串列
        /// </summary>
        public List<string> FileList { get; set; }
    }
AutoUpdateInfo.cs

7.2、通用類

作用:應用程式全域靜態常量,全域引數都在此設定,方便統一管理,

    /// <summary>
    /// 應用程式全域靜態常量
    /// </summary>
    public static class GlobalParam
    {
        /// <summary>
        /// 遠端自動更新資訊XML檔案名
        /// </summary>
        public const string AutoUpdateInfo_XmlFileName = "AutoUpdateInfo.xml";

        /// <summary>
        /// 遠端自動更新目錄
        /// </summary>
        public const string AutoUpdateDir = "AutoUpdateDir";

        /// <summary>
        /// 遠端自動更新檔案存放目錄
        /// </summary>
        public const string RemoteDir = "AutoUpdateFiles";

        /// <summary>
        /// 主執行緒名
        /// </summary>
        public const string MainProcess = "AutoUpdaterTest";
    }
GlobalParam.cs

7.3、Window 表單

1)新建一個Windows 表單Main,

    public partial class Main : Form
    {
        //自動更新目錄路徑
        private static readonly string AutoUpdateDirPath = Application.StartupPath + @"\" + GlobalParam.AutoUpdateDir;
        //自動更新資訊XML檔案路徑
        private static readonly string AutoUpdateInfoXmlPath = Path.Combine(AutoUpdateDirPath, GlobalParam.AutoUpdateInfo_XmlFileName);
        //自動更新檔案目錄路徑
        private static readonly string RemoteDirPath = Application.StartupPath + @"\" + GlobalParam.AutoUpdateDir + @"\" + GlobalParam.RemoteDir;

        public Main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 表單加載
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(RemoteDirPath))
            {
                Directory.CreateDirectory(RemoteDirPath);
            }
            LoadBaseInfo();
            LoadDirectoryFileList();
        }

        /// <summary>
        /// 重繪
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadBaseInfo();
            LoadDirectoryFileList();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void LoadBaseInfo()
        {
            dtUpdateTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            txtNewVersion.Text = GetMainProcessFileVersion();
            CreateHeaderAndFillListView();
        }

        /// <summary>
        /// 獲取主程式檔案版本
        /// </summary>
        /// <returns></returns>
        private string GetMainProcessFileVersion()
        {
            string fileVersion = "";
            if (File.Exists(RemoteDirPath + "\\" + GlobalParam.MainProcess + ".exe"))   //如果更新中有主程式檔案
            {
                FileVersionInfo info = FileVersionInfo.GetVersionInfo(RemoteDirPath + "\\" + GlobalParam.MainProcess + ".exe");
                fileVersion = info.FileVersion;
            }
            return fileVersion;
        }

        /// <summary>
        /// 添加ListView列名
        /// </summary>
        private void CreateHeaderAndFillListView()
        {
            lstFileList.Columns.Clear();
            int lvWithd = lstFileList.Width;
            ColumnHeader columnHeader;

            //First Header
            columnHeader = new ColumnHeader
            {
                Text = "#",
                Width = 38
            };
            lstFileList.Columns.Add(columnHeader);

            //Second Header
            columnHeader = new ColumnHeader
            {
                Text = "檔案名",
                Width = (lvWithd - 38) / 2
            };
            lstFileList.Columns.Add(columnHeader);

            //Third Header
            columnHeader = new ColumnHeader
            {
                Text = "更新路徑",
                Width = (lvWithd - 38) / 2
            };
            lstFileList.Columns.Add(columnHeader);
        }

        /// <summary>
        /// 加載目錄檔案串列
        /// </summary>
        private void LoadDirectoryFileList()
        {
            if (!Directory.Exists(RemoteDirPath))
            {
                Directory.CreateDirectory(RemoteDirPath);
            }
            FileHelper fileHelper = new FileHelper(RemoteDirPath);
            var fileArrary = fileHelper.GetUpdateList(fileHelper.GetAllFilesInDirectory(RemoteDirPath)).ToList();
            var lastFile = fileArrary.FirstOrDefault(s => s == GlobalParam.MainProcess + ".exe");
            //exe作為最后的檔案更新,防止更新程序中出現網路錯誤,導致檔案未全部更新,
            if (lastFile != null)
            {
                fileArrary.Remove(lastFile);
                fileArrary.Add(lastFile);
            }
            PopulateListViewWithArray(fileArrary.ToArray());
        }

        /// <summary>
        /// 使用路徑字符陣列填充串列
        /// </summary>
        /// <param name="strArray"></param>
        private void PopulateListViewWithArray(string[] strArray)
        {
            lstFileList.Items.Clear();
            if (strArray != null)
            {
                //只過濾根目錄下的特殊檔案
                strArray = strArray.Where(s => !new string[] { GlobalParam.AutoUpdateInfo_XmlFileName }.Contains(s.Substring(s.IndexOf('\\') + 1))).ToArray();
                for (int i = 0; i < strArray.Length; i++)
                {
                    ListViewItem lvi = new ListViewItem
                    {
                        Text = (i + 1).ToString()
                    };
                    int intStart = strArray[i].LastIndexOf('\\') + 1;
                    lvi.SubItems.Add(strArray[i].Substring(intStart, strArray[i].Length - intStart));
                    lvi.SubItems.Add(strArray[i]);
                    lstFileList.Items.Add(lvi);
                }
            }
        }

        /// <summary>
        /// 生成更新XML檔案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBuild_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNewVersion.Text))
            {
                MessageBox.Show("更新版本號不能為空,", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtNewVersion.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtMainProcessName.Text))
            {
                MessageBox.Show("主行程名不能為空,", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtMainProcessName.Focus();
                return;
            }

            AutoUpdateInfo info = new AutoUpdateInfo()
            {
                NewVersion = txtNewVersion.Text.Trim(),
                UpdateTime = dtUpdateTime.Value.ToString("yyyy-MM-dd"),
                UpdateContent = txtUpdateContent.Text,
                FileList = lstFileList.Items.Cast<ListViewItem>().Select(s => s.SubItems[2].Text).ToList()
            };

            string xmlValue = https://www.cnblogs.com/atomy/p/XmlUtility.Serializer(typeof(AutoUpdateInfo), info);
            using (StreamWriter sw = new StreamWriter(AutoUpdateInfoXmlPath))
            {
                sw.WriteLine(xmlValue);
                sw.Flush();
                sw.Close();
            }
            MessageBox.Show("生成成功,", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 打開本地目錄
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe")
            {
                Arguments = AutoUpdateDirPath
            };
            Process.Start(psi);
        }
    }
Main.cs

2)在bin\Debug\下新建一個AutoUpdateDir檔案夾,然后再在AutoUpdateDir下新建一個AutoUpdateFiles檔案夾,

3)在AutoUpdaterTest中,將程式集版本及檔案版本都改成1.0.0.1并重新生成,接著將AutoUpdaterTest.exe拷貝到AutoUpdateFiles下,最后將程式集版本及檔案版本都改回1.0.0.0,

4)此時運行AutoUpdateXmlBuilder,點擊生成更新XML檔案即打包成功,程式會自動在AutoUpdateDir下生成打包資訊檔案AutoUpdateInfo.xml,

7.4、應用程式主入口

    internal static class Program
    {
        /// <summary>
        /// 應用程式的主入口點,
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Main());
        }

        /// <summary>
        /// UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";
            var error = e.Exception;

            if (error != null)
            {
                strError = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外型別:{error.GetType().Name}\r\n例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}\r\n來源資訊:{error.Source}\r\n";
            }
            else
            {
                strError = $"Application ThreadException:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 非UI執行緒未捕獲例外處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string strError = "", strLog = "", strDateInfo = DateTime.Now.ToString() + " 出現應用程式未處理的例外:\r\n";

            if (e.ExceptionObject is Exception error)
            {
                strError = strDateInfo + $"例外訊息:{error.Message}";
                strLog = strDateInfo + $"例外訊息:{error.Message}\r\n堆疊資訊:{error.StackTrace}";
            }
            else
            {
                strError = $"Application UnhandledError:{e}";
            }

            WriteLog(strLog);
            MessageBox.Show(strError, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 寫入日志
        /// </summary>
        /// <param name="strLog"></param>
        private static void WriteLog(string strLog)
        {
            string dirPath = @"Log\XmlBuilder", fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            string strLine = "----------------------------------------------------------------------------------------------------";

            FileUtility.WriteFile(Path.Combine(dirPath, fileName), strLog);
            FileUtility.WriteFile(Path.Combine(dirPath, fileName), strLine);
        }
    }
Program.cs

八、遠程服務端配置

注:此處為本機測驗,

1)在某個盤符如E盤下新建一個AutoUpdate檔案夾,將AutoUpdateXmlBuilder打包檔案夾AutoUpdateDir拷貝到AutoUpdate檔案夾下,

2)在IIS中新建一個網站,對應的虛擬目錄為E:\AutoUpdate,同時將埠設定為6600,

3)運行AutoUpdaterTest,如出現自動更新器即代表成功,

原始碼下載

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/308050.html

標籤:WinForm

上一篇:Cannot find setup engine instance. Visual Studio 2017 安裝拓展失敗解決方案

下一篇:WinForm使用WebBrowser控制元件加載百度地圖api 2.0版本不顯示

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more