C# 備份、還原、拷貝遠程檔案夾

來源:互聯網
上載者:User

標籤:compress   combine   mes   parent   pat   工作   拷貝   rac   except   

最近一直都很忙,非常抱歉好久沒有寫過部落格了。最近遇到拷貝遠程檔案的一些工作,比如我們發布的web網站的時候,開發提供一個zip壓縮包,我們需要上傳到遠端伺服器A,然後在部署(檔案拷貝)到遠程環境B和C,ABC都在一個區域網路裡面。

首先我們需要一個工具類來轉換檔路徑,本地地址與遠程地址的轉換 比如192.168.0.1上的D:\test 轉換 為\\192.168.0.1\D$\test,檔案路徑的拼接,

 public class PathUtil    {        public static string GetRemotePath(string ip, string localPath)        {            if (!localPath.Contains(":"))            {                throw new Exception($"{localPath}路徑必須是全路徑且是本地路徑");            }            localPath = localPath.Replace(":", "$");            return $@"\\{ip}\{localPath}";        }        public static string GetLocaPath(string remotePath)        {            int index = remotePath.IndexOf("$");            if (index < 1)            {                throw new Exception($"{remotePath}路徑必須包含磁碟資訊");            }            string temp = remotePath.Substring(index - 1);            temp = temp.Replace("$", ":");            return temp;        }        public static string Combine(string path1, string path2)        {            path1 = path1.Trim();            path2 = path2.Trim();            if (path1.EndsWith("\\") && path2.StartsWith("\\"))            {                string ret = (path1 + path2).Replace("\\", "");                return ret;            }            else if (!path1.EndsWith("\\") && !path2.StartsWith("\\"))            {                return path1 + "\\" + path2;            }            // if ((path1.EndsWith("\\") && !path2.StartsWith("\\")) ||            //(!path1.EndsWith("\\") && path2.StartsWith("\\"))) { }            return path1 + path2;        }    }

備份遠程目錄的檔案夾 (首先備份遠程A目錄到本地臨時檔案zip->拷貝到遠程B->刪除本地臨時檔案zip)

還原遠程檔案(部署發布包)(遠程檔案解壓到本地臨時目錄->拷貝到目標伺服器->刪除本地臨時目錄)

檔案夾得拷貝就比較簡單,遞迴調用檔案複製就okay了,比如 \\192.168.0.1\D$\test 拷貝到  \\192.168.0.2\D$\test下 (建議先刪除存在檔案在拷貝)。

相關code如下:

  #region 檔案操作部分        /// <summary>        /// 把一個目錄下的檔案拷貝的目標目錄下        /// </summary>        /// <param name="sourceFolder">來源目錄</param>        /// <param name="targerFolder">目標目錄</param>        /// <param name="removePrefix">移除檔案名稱部分路徑</param>        public void CopyFiles(string sourceFolder, string targerFolder, string removePrefix = "")        {            if (string.IsNullOrEmpty(removePrefix))            {                removePrefix = sourceFolder;            }            if (!Directory.Exists(targerFolder))            {                Directory.CreateDirectory(targerFolder);            }            DirectoryInfo directory = new DirectoryInfo(sourceFolder);            //擷取目錄下的檔案            FileInfo[] files = directory.GetFiles();            foreach (FileInfo item in files)            {                if (item.Name == "Thumbs.db")                {                    continue;                }                string tempPath = item.FullName.Replace(removePrefix, string.Empty);                tempPath = targerFolder + tempPath;                FileInfo fileInfo = new FileInfo(tempPath);                if (!fileInfo.Directory.Exists)                {                    fileInfo.Directory.Create();                }                File.Delete(tempPath);                item.CopyTo(tempPath, true);            }            //擷取目錄下的子目錄            DirectoryInfo[] directors = directory.GetDirectories();            foreach (var item in directors)            {                CopyFiles(item.FullName, targerFolder, removePrefix);            }        }        /// <summary>        /// 備份遠程檔案夾為zip檔案        /// </summary>        /// <param name="sourceFolder">備份目錄</param>        /// <param name="targertFile">目標檔案</param>        /// <returns></returns>        public bool BackZip(string sourceFolder, string targertFile)        {            string tempfileName = PathUtil.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".zip");            bool ret = false;            try            {                ZipFile.CreateFromDirectory(sourceFolder, tempfileName, CompressionLevel.Optimal, false);                var parentDirect = (new FileInfo(targertFile)).Directory;                if (!parentDirect.Exists)                {                    parentDirect.Create();                }                File.Copy(tempfileName, targertFile, true);                ret = true;            }            catch (Exception ex)            {                throw new Exception($"備份目錄{sourceFolder}出錯{ex.Message}");            }            finally            {                if (File.Exists(tempfileName))                {                    File.Delete(tempfileName);                }            }            return ret;        }        /// <summary>        /// 把遠程檔案還原為遠程目錄        /// </summary>        /// <param name="sourceFile">遠程檔案</param>        /// <param name="targetFolder">遠程目錄</param>        /// <returns></returns>        public bool RestoreZip(string sourceFile, string targetFolder)        {            string tempFolderName = PathUtil.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());            bool ret = false;            try            {                using (ZipArchive readZip = ZipFile.OpenRead(sourceFile))                {                    readZip.ExtractToDirectory(tempFolderName);                }                string copyFolder = tempFolderName;                //if (!Directory.GetFiles(copyFolder).Any() && Directory.GetDirectories(copyFolder).Length == 1)                //{                //    copyFolder = Directory.GetDirectories(copyFolder)[0];                //}                CopyFiles(copyFolder, targetFolder, copyFolder);                ret = true;            }            catch (Exception ex)            {                throw new Exception($"發布檔案{sourceFile}到{targetFolder}出錯{ex.Message}");            }            finally            {                if (Directory.Exists(tempFolderName))                {                    Directory.Delete(tempFolderName, true);                }            }            return ret;        }        #endregion

 

C# 備份、還原、拷貝遠程檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.