博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 备份、还原、拷贝远程文件夹
阅读量:4602 次
发布时间:2019-06-09

本文共 5654 字,大约阅读时间需要 18 分钟。

最近一直都很忙,非常抱歉好久没有写过博客了。最近遇到拷贝远程文件的一些工作,比如我们发布的web站点的时候,开发提供一个zip压缩包,我们需要上传到远程的服务器A,然后在部署(文件拷贝)到远程环境B和C,ABC都在一个局域网里面。文件压缩需要引用 System.IO.Compression和System.IO.Compression.FileSystem

首先我们需要一个工具类来转换文件路径,本地地址与远程地址的转换 比如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 文件操作部分        ///         /// 把一个目录下的文件拷贝的目标目录下        ///         /// 源目录        /// 目标目录        /// 移除文件名部分路径        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);            }        }        ///         /// 备份远程文件夹为zip文件        ///         /// 备份目录        /// 目标文件        /// 
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; } /// /// 把远程文件还原为远程目录 /// /// 远程文件 /// 远程目录 ///
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

 

转载于:https://www.cnblogs.com/majiang/p/7533648.html

你可能感兴趣的文章
Java求职实战之继承和多态
查看>>
手机Fildder抓包_监控应用请求
查看>>
【SoftwareTesting】Homework2
查看>>
Java常见笔试、面试题目深度剖析
查看>>
个人课程总结
查看>>
Android_xml背景色的值
查看>>
遍历数组排序,负数在左,正数在右
查看>>
wangkoala杂题总集(根据个人进度选更)
查看>>
正则表达式
查看>>
android端,webview内url跳转到app本地
查看>>
列表 list 容器类型数据(str字符串, list列表, tuple元组, set集合, dict字典)--->元组 tuple-->字符串 str...
查看>>
Mysql-sql查询顺序
查看>>
php 钩子函数原理 解析
查看>>
Windows Store App 全球化:在后台代码中引用字符串资源
查看>>
Sass 与SCSS
查看>>
Java中 ThreadPoolExecutor 类学习笔记
查看>>
Python_基于Python同Linux进行交互式操作实现通过堡垒机访问目标机
查看>>
Python 基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控
查看>>
字典问题
查看>>
webBrowser1.Document.Cookie取不到HttpOnly的Cookie,取Cookie不完整【转】
查看>>