最近一直都很忙,非常抱歉好久没有写过博客了。最近遇到拷贝远程文件的一些工作,比如我们发布的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 < )
{
throw new Exception($"{remotePath}路径必须包含磁盘信息");
} string temp = remotePath.Substring(index - );
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# 备份、还原、拷贝远程文件夹的更多相关文章

  1. C# 拷贝指定文件夹下的所有文件及其文件夹到指定目录

    要拷贝的文件及其文件夹结构 其中.lab文件不能覆盖 /// <summary> /// 拷贝oldlab的文件到newlab下面 /// </summary> /// < ...

  2. 设置好ftp后用xftp连接提示无法打开,无法显示远程文件夹

    原文:设置好ftp后用xftp连接提示无法打开,无法显示远程文件夹 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/the_victory/artic ...

  3. 实测总结 挂载远程文件夹方案 smb ftp sftp nfs webdav

    挂载远程文件夹的方法有: 1.smb 2.ftp 3.sftp 4.nfs 5.webdav 1.smb windows局域网使用的协议,windows网上邻居发现的共享文件夹即使用的smb协议,可以 ...

  4. xftp 提示无法显示远程文件夹

    在用xftp远程服务器,打开文件夹的时候一直提示"无法显示远程文件夹" 解决方案: 1.网上大多解决方案是文件->属性->选项->将使用被动模式选项去掉即可 2. ...

  5. git删除远程文件夹或文件的方法

    由于本地修改了文件夹大全名大小写的原因,同步到git上并不区分大小写,造成了一些文件同步不了,所以要先把git远程库上文件夹删除掉,然后再重新同步 如下,我把src里的全部移除,但是本地文件还保留. ...

  6. cmd命令 拷贝某文件夹及其子文件夹文件到其它文件夹

    @ECHO OFF cd/d %H:\FileLoc\CNET&cd.. ::echo 拷贝"%H:\FileLoc\CNET"中文件到"H:\FileLocTe ...

  7. sublime sftp 打开远程文件夹

    2014-04-29 13:19:09 总结: 本文介绍两种方法,推荐第二种方法(samba+windows映射) 先贴出sublime打开远程(Linux)目录所需的配置文件(sublime是通过s ...

  8. java拷贝指定文件夹下的指定文件类型

    例如:把C:\Windows\SysWOW64下的所有dll文件拷贝到C:\Users\Administrator\Desktop\64dll这个目录 package com.xiaostudy.co ...

  9. 使用diff或者vimdiff比较远程文件(夹)与本地文件夹

    方法1:管道给diff $ssh eric@192.168.1.11 "cat ~/remote_file.txt" | diff - ~/local_file.txt 如果 Fi ...

随机推荐

  1. LeetCode(60): 第k个排列

    Medium! 题目描述: 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" ...

  2. hdu5178 尺取

    会爆int /* 给定数轴上一些点对,问有多少点对之间的距离差不超过k 点对排序后尺取法:枚举每个左边界,找到一个右边界使得 */ #include<bits/stdc++.h> #def ...

  3. python接口自动化测试十三:url编码与解码

    # url编码与解码 from urllib import parse url = 'http://zzk.cnblogs.com/s/blogpost?Keywords=中文' a = '中文' b ...

  4. SpringBank 开发日志 重新设计Action调用Service的参数传递 使用泛型解决类型转换问题

    之前想的比较简单,请求到达controller的时候,传给action的参数没有经过任何封装,就是一个Map.然后action再调用service的时候,传递的参数也是map @Controller ...

  5. POJ 2976 3111(二分-最大化平均值)

    POJ 2976 题意 给n组数据ai,bi,定义累计平均值为: 现给出一个整数k,要求从这n个数中去掉k个数后,最大累计平均值能有多大?(四舍五入到整数) 思路 取n−k个数,使得累计平均值最大. ...

  6. openstack安装-计算节点-neutron服务安装

    一.安装nettron相关服务 yum install openstack-neutron-linuxbridge ebtables ipset -y 二.快速配置配置  修改红色部分为计算节点的网卡 ...

  7. 让我们了解 Ceph 分布式存储

    前言 最近在学习 kubernetes 过程中,想实现 pod 数据的持久化.在调研的过程中,发现 ceph 在最近几年发展火热,也有很多案例落地企业.在选型方面,个人更加倾向于社区火热的项目,Glu ...

  8. HDU1711 Number Sequence KMP

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - HDU1711 题意概括 给T组数据,每组有长度为n和m的母串和模式串.判断模式串是否是母串的子串,如果是输出 ...

  9. Vijos1906 联合权值 NOIP2014Day1T2 树形动态规划

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - Vijos1906 题意概括 有一棵树,每一个节点都有一个权值w[i].下面说的x,y都是该树中的节点. 对于 ...

  10. tensorflow入门(1):构造线性回归模型

    今天让我们一起来学习如何用TF实现线性回归模型.所谓线性回归模型就是y = W * x + b的形式的表达式拟合的模型. 我们先假设一条直线为 y = 0.1x + 0.3,即W = 0.1,b = ...