从服务器远程地址下载更新文件(较新则更新,否则忽略)

今天记录的一个功能是从服务器远程地址下载更新文件,如果本地文件的最后修改时间比远程地址的文件的新则忽略。

验证域名的正则表达式(域名可带端口):

"((http|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?"

验证远程地址是否合法及是否可访问的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

namespace demo1
{
    public class UriUtil
    {
        /// <summary>
        /// 检测是否为合法的URL格式
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static bool CheckIsUrl(string strValue)
        {
            return CheckIsFormat(@"((http|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?", strValue);
        }

        public static bool CheckIsFormat(string strRegex, string strValue)
        {
            if (!string.IsNullOrWhiteSpace(strValue))
            {
                var regex = new Regex(strRegex);
                return regex.IsMatch(strValue);
            }
            return false;
        }

        /// <summary>
        /// 检查url是否能访问
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static bool CheckUrl(string url, int timeOut = 5000)
        {
            if (string.IsNullOrWhiteSpace(url))
                return false;
            if (!CheckIsUrl(url))
                return false;
            try
            {
                var myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "HEAD";
                myRequest.Timeout = timeOut;
                var myResponse = (HttpWebResponse)myRequest.GetResponse();
                var res = myResponse.StatusCode == HttpStatusCode.OK;
                myResponse.Close();
                return res;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

从远程地址下载更新文件功能实现:

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

namespace demo1
{
    public class FileUtil
    {
        /// <summary>
        /// 从远程地址更新文件(较新则覆盖,否则忽略)
        /// </summary>
        /// <param name="url">远程地址</param>
        /// <param name="localFolder">本地存储路径</param>
        /// <param name="fileName">文件名</param>
        public static void UpdateFileFormUrl(string url, string localFolder, string fileName)
        {
            try
            {
                var filePath = Path.Combine(url, fileName);
                DateTime remoteLastDate = new DateTime(), localLastDate = new DateTime();
                var localFilePath = Path.Combine(localFolder, fileName);

                if (File.Exists(localFilePath))
                {
                    FileInfo fileInfo = new FileInfo(localFilePath);
                    localLastDate = fileInfo.LastWriteTime;
                    fileInfo = null;
                }

                if (UriUtil.CheckUrl(filePath))
                {
                    var req = WebRequest.Create(filePath);
                    req.Timeout = 15 * 1000;
                    var res = req.GetResponse();
                    WebHeaderCollection header = res.Headers;
                    string lastModify = header["Last_Modified"];
                    if (!string.IsNullOrEmpty(lastModify))
                        DateTime.TryParse(lastModify, out remoteLastDate);
                    if (remoteLastDate > localLastDate)
                    {
                        var fileLength = res.ContentLength;
                        if (fileLength != 0)
                        {
                            using (var srm = res.GetResponseStream())
                            {
                                var bufferByte = new byte[fileLength];
                                int allByte = bufferByte.Length;
                                int startByte = 0;
                                while (fileLength > 0)
                                {
                                    int downByte = srm.Read(bufferByte, startByte, allByte);
                                    if (downByte == 0)
                                        break;
                                    startByte += downByte;
                                    allByte -= downByte;
                                }
                                string downFileName = localFilePath;
                                using (var fs = new FileStream(downFileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fs.Write(bufferByte, 0, bufferByte.Length);
                                }
                            }
                        }
                    }
                    res.Close();
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Update file {0} error:", fileName) + e.Message);
            }
        }
    }
}

版权声明:若无特殊注明,本文为《奕独客》原创,转载请保留文章出处。
本文链接:从服务器远程地址下载更新文件(较新则更新,否则忽略) [https://www.yiduk.com/源码分享/22.html]
正文到此结束

热门推荐