C# 备份、还原、拷贝远程文件夹
最近一直都很忙,非常抱歉好久没有写过博客了。最近遇到拷贝远程文件的一些工作,比如我们发布的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# 备份、还原、拷贝远程文件夹的更多相关文章
- C# 拷贝指定文件夹下的所有文件及其文件夹到指定目录
要拷贝的文件及其文件夹结构 其中.lab文件不能覆盖 /// <summary> /// 拷贝oldlab的文件到newlab下面 /// </summary> /// < ...
- 设置好ftp后用xftp连接提示无法打开,无法显示远程文件夹
原文:设置好ftp后用xftp连接提示无法打开,无法显示远程文件夹 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/the_victory/artic ...
- 实测总结 挂载远程文件夹方案 smb ftp sftp nfs webdav
挂载远程文件夹的方法有: 1.smb 2.ftp 3.sftp 4.nfs 5.webdav 1.smb windows局域网使用的协议,windows网上邻居发现的共享文件夹即使用的smb协议,可以 ...
- xftp 提示无法显示远程文件夹
在用xftp远程服务器,打开文件夹的时候一直提示"无法显示远程文件夹" 解决方案: 1.网上大多解决方案是文件->属性->选项->将使用被动模式选项去掉即可 2. ...
- git删除远程文件夹或文件的方法
由于本地修改了文件夹大全名大小写的原因,同步到git上并不区分大小写,造成了一些文件同步不了,所以要先把git远程库上文件夹删除掉,然后再重新同步 如下,我把src里的全部移除,但是本地文件还保留. ...
- cmd命令 拷贝某文件夹及其子文件夹文件到其它文件夹
@ECHO OFF cd/d %H:\FileLoc\CNET&cd.. ::echo 拷贝"%H:\FileLoc\CNET"中文件到"H:\FileLocTe ...
- sublime sftp 打开远程文件夹
2014-04-29 13:19:09 总结: 本文介绍两种方法,推荐第二种方法(samba+windows映射) 先贴出sublime打开远程(Linux)目录所需的配置文件(sublime是通过s ...
- java拷贝指定文件夹下的指定文件类型
例如:把C:\Windows\SysWOW64下的所有dll文件拷贝到C:\Users\Administrator\Desktop\64dll这个目录 package com.xiaostudy.co ...
- 使用diff或者vimdiff比较远程文件(夹)与本地文件夹
方法1:管道给diff $ssh eric@192.168.1.11 "cat ~/remote_file.txt" | diff - ~/local_file.txt 如果 Fi ...
随机推荐
- 洛谷P2239 螺旋矩阵
传送门 分析:将整个矩阵看成 "回" 形状的分层结构,然后进行去层处理,使得要求得 \((i,j)\) 处于最外层,然后再分情况讨论.最外面的一层共有数: $ 4 * n - 4 ...
- hdu1698
/*区间更新*/#include <cstdio> #include <algorithm> using namespace std; #define lson l , m , ...
- js事件驱动函数
输入框 获得光标的这个行为叫做获取焦点 失去光标的这个行为叫做失去焦点 blur 失去焦点 1.获取标签的时候,一定要先等页面加载完成,再去获取这个标签. 可以将整个script代码写在body的下面 ...
- CSS 滤镜
声明: web前端学习笔记,欢迎大神指点.联系QQ:1522025433. CSS样式表是一种为超文本标签语言提供增强补充服务的技术,可对每一个html的标签做精雕细刻的修饰.只用html制作的网页, ...
- list的遍历
package list; import java.util.ArrayList;import java.util.Iterator;import java.util.List; /* * list的 ...
- 【AtCoder】AGC018
A - Getting Difference 我们肯定可以得到这些数的gcd,然后判断每个数减整数倍的gcd能否得到K #include <bits/stdc++.h> #define f ...
- python全栈开发day49-jquery的位置信息、事件流、事件对象,事件委托,事件绑定和解绑
一.昨日内容回顾 1. jQuery的属性操作 1) html属性操作:attr 2) DOM属性操作:prop 3) 类样式操作:addClass.removeClass.toggleClas ...
- kafka中生产者和消费者API
使用idea实现相关API操作,先要再pom.xml重添加Kafka依赖: <dependency> <groupId>org.apache.kafka</groupId ...
- 网络流24题 第五题 - PowerOJ1740 CodeVS1905 圆桌问题 二分图多重匹配 网络最大流
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - PowerOJ1740 - 有SPJ - 推荐 题目传送门 - CodeVS1905 - 无SPJ - 0% ...
- 006 Spark中的wordcount以及TopK的程序编写
1.启动 启动HDFS 启动spark的local模式./spark-shell 2.知识点 textFile: def textFile( path: String, minPartitions: ...