当前位置: 首页 > news >正文

C# 备份文件夹

C# 备份目标文件夹

方法1:通过 递归 或者 迭代 结合 C# 方法

参数说明:

  • sourceFolder:源文件夹路径
  • destinationFolder:目标路径
  • excludeNames:源文件夹中不需备份的文件或文件夹路径哈希表
  • errorLog:输出错误log

递归实现

		private bool CopyAllFolder(string sourceFolder, string destinationFolder, HashSet<string> excludeNames, out string errorLog){errorLog = string.Empty;try{if (!Directory.Exists(destinationFolder)){Directory.CreateDirectory(destinationFolder);}string[] directories = Directory.GetDirectories(sourceFolder);string[] files = Directory.GetFiles(sourceFolder);foreach (string file in files){if (excludeNames.Count != 0 && excludeNames.Contains(file)){continue;}try{if (!BRTools.IsFileReady(file) || !BRTools.IsNotFileInUse(file, out errorLog)) // 检测文件是否被占用{return false;}string destinationFile = Path.Combine(destinationFolder, Path.GetFileName(file));File.Copy(file, destinationFile, true);}catch (Exception ex){errorLog += $"Error copying file '{file}': {ex.Message}\n";return false;}}foreach (string directory in directories){if (excludeNames.Count != 0 && excludeNames.Contains(directory)){continue;}string destinationSubFolder = Path.Combine(destinationFolder, Path.GetFileName(directory));if (!CopyAllFolder(directory, destinationSubFolder, excludeNames, out string subfolderErrorLog)){errorLog += subfolderErrorLog;return false;}}return true;}catch (Exception ex){errorLog = $"Error during folder copy: Message = '{ex.Message}', StackTrace = '{ex.StackTrace}'\n";return false;}}

迭代实现:

        private bool CopyAllFolder(string sourceFolder, string destinationFolder, HashSet<string> excludeNames, out string errorLog){errorLog = string.Empty;try{if (!Directory.Exists(destinationFolder)){Directory.CreateDirectory(destinationFolder);}Stack<string> directoryStack = new Stack<string>();directoryStack.Push(sourceFolder);while (directoryStack.Count > 0){string currentDirectory = directoryStack.Pop();string[] directories = Directory.GetDirectories(currentDirectory);string[] files = Directory.GetFiles(currentDirectory);foreach (string file in files){if (excludeNames.Count != 0 && excludeNames.Contains(file)){continue;}try{if (!BRTools.IsFileReady(file) || !BRTools.IsNotFileInUse(file, out errorLog)){return false;}string destinationFile = Path.Combine(destinationFolder, Path.GetFileName(file));File.Copy(file, destinationFile, true);}catch (Exception ex){errorLog += $"Error copying file '{file}': {ex.Message}\n";return false;}}foreach (string directory in directories){if (excludeNames.Count != 0 && excludeNames.Contains(directory)){continue;}string destinationSubFolder = Path.Combine(destinationFolder, Path.GetFileName(directory));if (!CopyAllFolder(directory, destinationSubFolder, excludeNames, out string subfolderErrorLog)){errorLog += subfolderErrorLog;return false;}directoryStack.Push(directory);}}return true;}catch (Exception ex){errorLog = $"Error during folder copy: Message = '{ex.Message}', StackTrace = '{ex.StackTrace}'\n";return false;}}

方法2:利用 Windows API

		[DllImport("shell32.dll", CharSet = CharSet.Auto)]public static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]public struct SHFILEOPSTRUCT{public IntPtr hwnd;public int wFunc;public string pFrom;public string pTo;public short fFlags;public bool fAnyOperationsAborted;public IntPtr hNameMappings;}const int FO_COPY = 0x0002;const int FOF_NOCONFIRMATION = 0x0010;const int FOF_SILENT = 0x0004;const int FOF_NO_UI = FOF_NOCONFIRMATION | FOF_SILENT;private bool CopyDirectory(string sourceDir, string destDir, out string errorLog){errorLog = string.Empty;try{SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT();fileOp.wFunc = FO_COPY;fileOp.pFrom = sourceDir + '\0' + '\0';  // Must end with double null characterfileOp.pTo = destDir + '\0' + '\0';     // Must end with double null character//fileOp.fFlags = FOF_NO_UI;fileOp.fFlags = FOF_NO_UI | FOF_NOCONFIRMATION;  // 忽略UI和确认对话框int result = SHFileOperation(ref fileOp);// 检查返回值if (result != 0){errorLog = $"SHFileOperation failed with error code: {result}";return false;}return true;}catch (Exception ex){errorLog = $"Failed to copy the entire folder '{sourceDir}': Message = '{ex.Message}', StackTrace = '{ex.StackTrace}'\n";return false;}}private bool CopyFolder(string sourceFolder, string destinationFolder, HashSet<string> excludeNames, out string errorLog){errorLog = string.Empty;try{if (!CopyDirectory(sourceFolder, destinationFolder, out errorLog)){this.logger.Warning($"errorLog: {errorLog}");return false;}if (excludeNames.Count != 0){foreach (var item in excludeNames){var targetPath = Path.Combine(destinationFolder, GetSonFolderPath(sourceFolder, item)); // 获取已备份路径下需排除的文件夹或文件路径if (Directory.Exists(item)){                                DeleteDir(targetPath);}if(File.Exists(item)){DeleteDir(targetPath);}}}return true;}catch(Exception ex){errorLog = $"Error during folder copy, and exception is: Message = '{ex.Message}', StackTrace = '{ex.StackTrace}'\n";return false;}}private string GetSonFolderPath(string folderPath, string targetPath){string result = string.Empty;try{folderPath = folderPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;if (!isFilePath(targetPath)){targetPath = targetPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;}else{targetPath = Path.GetDirectoryName(targetPath).TrimEnd(Path.DirectorySeparatorChar);}if (targetPath.StartsWith(folderPath, StringComparison.OrdinalIgnoreCase)){result = targetPath.Substring(folderPath.Length);}}catch (Exception){result = string.Empty;}return result;}private bool isFilePath(string targetPath){if (Path.HasExtension(targetPath) && File.Exists(targetPath))return true;return false;}private void DeleteFile(string file){if (File.Exists(file)){FileInfo fi = new FileInfo(file);if (fi.IsReadOnly){fi.IsReadOnly = false;}File.Delete(file);}}private void DeleteDir(string dir){if (Directory.Exists(dir)){foreach (string childName in Directory.GetFileSystemEntries(dir)){if (File.Exists(childName)){FileInfo fi = new FileInfo(childName);if (fi.IsReadOnly){fi.IsReadOnly = false;}File.Delete(childName);}elseDeleteDir(childName);}Directory.Delete(dir, true);}}

注意:方法2有一个漏洞,该方法无法成功捕捉到源文件夹下被占用的文件信息!

相关文章:

C# 备份文件夹

C# 备份目标文件夹 方法1&#xff1a;通过 递归 或者 迭代 结合 C# 方法 参数说明&#xff1a; sourceFolder&#xff1a;源文件夹路径destinationFolder&#xff1a;目标路径excludeNames&#xff1a;源文件夹中不需备份的文件或文件夹路径哈希表errorLog&#xff1a;输出错…...

互联网信息泄露与安全扫描工具汇总

文章目录 1. 代码托管平台渠道泄露2. 网盘渠道泄露3. 文章渠道泄露4. 文档渠道泄露5. 暗网渠道泄露6. 互联网IP信誉度排查7. 网站挂马暗链扫描8. 互联网IP端口扫描9. 互联网资产漏洞扫描 1. 代码托管平台渠道泄露 https://github.com/ https://gitee.com/ https://gitcode.co…...

主导极点,传递函数零极点与时域模态

运动模态 控制系统的数学建模&#xff0c;可以采用微分方程或传递函数&#xff0c;两者具有相同的特征方程。在数学上&#xff0c;微分方程的解由特解和通解组成&#xff0c;具体求解过程可以参考&#xff1a;微分方程求解的三种解析方法。 如果 n n n阶微分方程&#xff0c;具…...

永恒之蓝漏洞利用什么端口

永恒之蓝&#xff08;EternalBlue&#xff09;是一个著名的漏洞&#xff0c;影响了 Windows 操作系统的 SMBv1 服务。它的漏洞编号是 CVE-2017-0144&#xff0c;该漏洞被用于 WannaCry 等勒索病毒的传播。 永恒之蓝漏洞利用的端口 永恒之蓝漏洞利用的是 SMB&#xff08;Server…...

网络安全与防范

1.重要性 随着互联网的发达&#xff0c;各种WEB应用也变得越来越复杂&#xff0c;满足了用户的各种需求&#xff0c;但是随之而来的就是各种网络安全的问题。了解常见的前端攻击形式和保护我们的网站不受攻击是我们每个优秀fronter必备的技能。 2.分类 XSS攻击CSRF攻击网络劫…...

Navicat 17 功能简介 | SQL 开发

Navicat 17 功能简介 | SQL 开发 随着 17 版本的发布&#xff0c;Navicat 也带来了众多的新特性&#xff0c;包括兼容更多数据库、全新的模型设计、可视化智能 BI、智能数据分析、可视化查询解释、高质量数据字典、增强用户体验、扩展 MongoDB 功能、轻松固定查询结果、便捷URI…...

嵌入式系统中的并行编程模型:汇总解析与应用

概述&#xff1a;随着嵌入式系统处理能力的不断提升&#xff0c;并行编程在其中的应用愈发广泛。本文深入探讨了多种专门为嵌入式设计的并行编程模型&#xff0c;包括任务队列模型、消息传递模型、数据并行模型、异构多核并行模型、实时任务调度模型以及函数式并行模型。详细阐…...

VulkanSamples编译记录

按照BUILD.md说明&#xff0c;先安装依赖项 sudo apt-get install git build-essential libx11-xcb-dev \libxkbcommon-dev libwayland-dev libxrandr-dev 然后创建一个新文件夹build&#xff0c;在该目录下更新依赖项 cd VulkanSamples mkdir build cd build python ../scr…...

使用FabricJS对大图像应用滤镜(巨坑)

背景:我司在canvas的渲染模板的宽高都大于2048px 都几乎接近4000px&#xff0c;就导致使用FabricJS的滤镜功能图片显示异常 新知识:滤镜是对图片纹理的处理 FabricJS所能支持的最大图片纹理是2048的 一但图片超出2048的纹理尺寸 当应用滤镜时&#xff0c;图像会被剪切或者是缩…...

网页502 Bad Gateway nginx1.20.1报错与解决方法

目录 网页报错的原理 查到的502 Bad Gateway报错的原因 出现的问题和尝试解决 问题 解决 网页报错的原理 网页显示502 Bad Gateway 报错原理是用户访问服务器时&#xff0c;nginx代理服务器接收用户信息&#xff0c;但无法反馈给服务器&#xff0c;而出现的报错。 查到…...

Spring基础分析02-BeanFactory与ApplicationContext

大家好&#xff0c;今天和大家一起学习整理一下Spring 的BeanFactory和ApplicationContext内容和区别~ BeanFactory和ApplicationContext是Spring IoC容器的核心组件&#xff0c;负责管理应用程序中的Bean生命周期和配置。我们深入分析一下这两个接口的区别、使用场景及其提供…...

Rerender A Video 技术浅析(五):对象移除与自动配色

Rerender A Video 是一种基于深度学习和计算机视觉技术的视频处理工具&#xff0c;旨在通过智能算法对视频进行重新渲染和优化。 一、对象移除模块 1. 目标检测 1.1 概述 目标检测是对象移除的第一步&#xff0c;旨在识别视频中需要移除的对象并生成相应的掩码&#xff08;m…...

Java项目实战II基于微信小程序的小区租拼车管理信息系统 (开发文档+数据库+源码)

目录 一、前言 二、技术介绍 三、系统实现 四、核心代码 五、源码获取 全栈码农以及毕业设计实战开发&#xff0c;CSDN平台Java领域新星创作者&#xff0c;专注于大学生项目实战开发、讲解和毕业答疑辅导。 一、前言 随着城市化进程的加速&#xff0c;小区居民对于出行方…...

【数字花园】数字花园(个人网站、博客)搭建经历汇总教程

目录 写在最最前面第一章&#xff1a;netlify免费搭建数字花园相关教程使用的平台步骤信息管理 第二章&#xff1a;本地部署数字花园数字花园网站本地手动部署方案1. 获取网站源码2.2 安装 Node.js 3. 项目部署3.1 安装项目依赖3.2 构建项目3.3 启动http服务器 4. 本地预览5. 在…...

WebRTC服务质量(03)- RTCP协议

一、前言&#xff1a; RTCP&#xff08;RTP Control Protocol&#xff09;是一种控制协议&#xff0c;与RTP&#xff08;Real-time Transport Protocol&#xff09;一起用于实时通信中的控制和反馈。RTCP负责监控和调节实时媒体流。通过不断交换RTCP信息&#xff0c;WebRTC应用…...

STM32F103单片机HAL库串口通信卡死问题解决方法

在上篇文章 STM32F103单片机使用STM32CubeMX创建IAR串口工程 中分享了使用cubeMX直接生成串口代码的方法&#xff0c;在测试的过程中无意间发现&#xff0c;串口会出现卡死的问题。 当串口一次性发送十几个数据的时候&#xff0c;串口感觉像卡死了一样&#xff0c;不再接收数据…...

Scala正则表达式

一、定义&#xff1a;正则表达式是一种用于匹配、查找和替换文本中特定模式的字符串。 使用方式&#xff1a;①定义一个正则 正则表达式应用场景&#xff1a;查找、验证、替换。 Ⅰ、查找 在目标字符串中&#xff0c;找到符合正则表达式规则要求的 子串。 方括号&#xff…...

每日一刷——二叉树的构建——12.12

第一题&#xff1a;最大二叉树 题目描述&#xff1a;654. 最大二叉树 - 力扣&#xff08;LeetCode&#xff09; 我的想法&#xff1a; 我感觉这个题目最开始大家都能想到的暴力做法就是遍历找到数组中的最大值&#xff0c;然后再遍历一遍&#xff0c;把在它左边的依次找到最大…...

Redis配置文件中 supervised指令

什么是Supervised&#xff1f; supervised模式允许Redis被外部进程管理器监控。通过这个选项&#xff0c;Redis能够在崩溃后自动重启&#xff0c;确保服务的高可用性。常见的进程管理器包括systemd和upstart。 开启方法 vim修改&#xff1a; sudo vi /etc/redis/redis.conf…...

OpenCV相机标定与3D重建(18)根据基础矩阵(Fundamental Matrix)校正两组匹配点函数correctMatches()的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 优化对应点的坐标。 cv::correctMatches 是 OpenCV 库中的一个函数&#xff0c;用于根据基础矩阵&#xff08;Fundamental Matrix&#xff09;校…...

MongoDB学习和应用(高效的非关系型数据库)

一丶 MongoDB简介 对于社交类软件的功能&#xff0c;我们需要对它的功能特点进行分析&#xff1a; 数据量会随着用户数增大而增大读多写少价值较低非好友看不到其动态信息地理位置的查询… 针对以上特点进行分析各大存储工具&#xff1a; mysql&#xff1a;关系型数据库&am…...

visual studio 2022更改主题为深色

visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中&#xff0c;选择 环境 -> 常规 &#xff0c;将其中的颜色主题改成深色 点击确定&#xff0c;更改完成...

YSYX学习记录(八)

C语言&#xff0c;练习0&#xff1a; 先创建一个文件夹&#xff0c;我用的是物理机&#xff1a; 安装build-essential 练习1&#xff1a; 我注释掉了 #include <stdio.h> 出现下面错误 在你的文本编辑器中打开ex1文件&#xff0c;随机修改或删除一部分&#xff0c;之后…...

第25节 Node.js 断言测试

Node.js的assert模块主要用于编写程序的单元测试时使用&#xff0c;通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试&#xff0c;通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...

MODBUS TCP转CANopen 技术赋能高效协同作业

在现代工业自动化领域&#xff0c;MODBUS TCP和CANopen两种通讯协议因其稳定性和高效性被广泛应用于各种设备和系统中。而随着科技的不断进步&#xff0c;这两种通讯协议也正在被逐步融合&#xff0c;形成了一种新型的通讯方式——开疆智能MODBUS TCP转CANopen网关KJ-TCPC-CANP…...

关于 WASM:1. WASM 基础原理

一、WASM 简介 1.1 WebAssembly 是什么&#xff1f; WebAssembly&#xff08;WASM&#xff09; 是一种能在现代浏览器中高效运行的二进制指令格式&#xff0c;它不是传统的编程语言&#xff0c;而是一种 低级字节码格式&#xff0c;可由高级语言&#xff08;如 C、C、Rust&am…...

浅谈不同二分算法的查找情况

二分算法原理比较简单&#xff0c;但是实际的算法模板却有很多&#xff0c;这一切都源于二分查找问题中的复杂情况和二分算法的边界处理&#xff0c;以下是博主对一些二分算法查找的情况分析。 需要说明的是&#xff0c;以下二分算法都是基于有序序列为升序有序的情况&#xf…...

短视频矩阵系统文案创作功能开发实践,定制化开发

在短视频行业迅猛发展的当下&#xff0c;企业和个人创作者为了扩大影响力、提升传播效果&#xff0c;纷纷采用短视频矩阵运营策略&#xff0c;同时管理多个平台、多个账号的内容发布。然而&#xff0c;频繁的文案创作需求让运营者疲于应对&#xff0c;如何高效产出高质量文案成…...

mac 安装homebrew (nvm 及git)

mac 安装nvm 及git 万恶之源 mac 安装这些东西离不开Xcode。及homebrew 一、先说安装git步骤 通用&#xff1a; 方法一&#xff1a;使用 Homebrew 安装 Git&#xff08;推荐&#xff09; 步骤如下&#xff1a;打开终端&#xff08;Terminal.app&#xff09; 1.安装 Homebrew…...

Unity UGUI Button事件流程

场景结构 测试代码 public class TestBtn : MonoBehaviour {void Start(){var btn GetComponent<Button>();btn.onClick.AddListener(OnClick);}private void OnClick(){Debug.Log("666");}}当添加事件时 // 实例化一个ButtonClickedEvent的事件 [Formerl…...