最近一直都很忙,非常抱歉好久没有写过博客了。最近遇到拷贝远程文件的一些工作,比如我们发布的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(30):与所有单词相关联的字串

    Hard! 题目描述: 给定一个字符串 s 和一些长度相同的单词 words.在 s 中找出可以恰好串联 words 中所有单词的子串的起始位置. 注意子串要与 words 中的单词完全匹配,中间不能 ...

  2. hdu5256 二分求LIS+思维

    解题的思路很巧,为了让每个数之间都留出对应的上升空间,使a[i]=a[i]-i,然后再求LIS 另外二分求LIS是比较快的 #include<bits/stdc++.h> #define ...

  3. python 全栈开发,Day24(复习,__str__和__repr__,__format__,__call__,__eq__,__del__,__new__,item系列)

    反射: 使用字符串数据类型的变量名来使用变量 wwwh即what,where,why,how  这4点是一种学习方法 反射 :使用字符串数据类型的变量名来使用变量 1.文件中存储的都是字符串 2.网络 ...

  4. 线程使用中常见的错误-“System.InvalidOperationException”线程间操作无效: 从不是创建控件“ ”的线程访问它。

    “System.InvalidOperationException”类型的未经处理的异常在 System.Windows.Forms.dll 中发生 其他信息: 线程间操作无效: 从不是创建控件“la ...

  5. String:(字符串)中常用的方法

    package stringyiwen; //字符串中常用的方法public class StringTest03 { public static void main(String[] args) { ...

  6. 《剑指offer》-递增数组中找到和为S的(最小)两个元素

    题目描述 输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. 输出描述: 对应每个测试案例,输出两个数,小的先输出. 首先 ...

  7. hdu 4707 仓鼠 记录深度 (BFS)

    题意:linji的仓鼠丢了,他要找回仓鼠,他在房间0放了一块奶酪,按照抓鼠手册所说,这块奶酪可以吸引距离它D的仓鼠,但是仓鼠还是没有出现,现在给出一张关系图,表示各个房间的关系,相邻房间距离为1,而且 ...

  8. Ubuntu 安装 OpenMPI

    1. 下载OpenMPI 在官网上下载最新版本的安装包,如:openmpi-1.8.4.tar.gz 2. 解压并进行配置 tar -zxvf openmpi-3.0.0.tar.gz cd open ...

  9. mac和Linux的环境变量设置

    摘抄自:http://hi.baidu.com/machao_pe/item/763d0ef12d32cd35fe3582db redhat和ubuntu中修改环境变量 2010-03-06 23:4 ...

  10. php 代码中的箭头“ ->”是什么意思

    类是一个复杂数据类型,这个类型的数据主要有属性.方法两种东西. 属性其实是一些变量,可以存放数据,存放的数据可以是整数.字符串,也可以是数组,甚至是类. 方法实际上是一些函数,用来完成某些功能. 引用 ...