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:通过 递归 或者 迭代 结合 C# 方法 参数说明: sourceFolder:源文件夹路径destinationFolder:目标路径excludeNames:源文件夹中不需备份的文件或文件夹路径哈希表errorLog:输出错…...
互联网信息泄露与安全扫描工具汇总
文章目录 1. 代码托管平台渠道泄露2. 网盘渠道泄露3. 文章渠道泄露4. 文档渠道泄露5. 暗网渠道泄露6. 互联网IP信誉度排查7. 网站挂马暗链扫描8. 互联网IP端口扫描9. 互联网资产漏洞扫描 1. 代码托管平台渠道泄露 https://github.com/ https://gitee.com/ https://gitcode.co…...
主导极点,传递函数零极点与时域模态
运动模态 控制系统的数学建模,可以采用微分方程或传递函数,两者具有相同的特征方程。在数学上,微分方程的解由特解和通解组成,具体求解过程可以参考:微分方程求解的三种解析方法。 如果 n n n阶微分方程,具…...
永恒之蓝漏洞利用什么端口
永恒之蓝(EternalBlue)是一个著名的漏洞,影响了 Windows 操作系统的 SMBv1 服务。它的漏洞编号是 CVE-2017-0144,该漏洞被用于 WannaCry 等勒索病毒的传播。 永恒之蓝漏洞利用的端口 永恒之蓝漏洞利用的是 SMB(Server…...
网络安全与防范
1.重要性 随着互联网的发达,各种WEB应用也变得越来越复杂,满足了用户的各种需求,但是随之而来的就是各种网络安全的问题。了解常见的前端攻击形式和保护我们的网站不受攻击是我们每个优秀fronter必备的技能。 2.分类 XSS攻击CSRF攻击网络劫…...
Navicat 17 功能简介 | SQL 开发
Navicat 17 功能简介 | SQL 开发 随着 17 版本的发布,Navicat 也带来了众多的新特性,包括兼容更多数据库、全新的模型设计、可视化智能 BI、智能数据分析、可视化查询解释、高质量数据字典、增强用户体验、扩展 MongoDB 功能、轻松固定查询结果、便捷URI…...
嵌入式系统中的并行编程模型:汇总解析与应用
概述:随着嵌入式系统处理能力的不断提升,并行编程在其中的应用愈发广泛。本文深入探讨了多种专门为嵌入式设计的并行编程模型,包括任务队列模型、消息传递模型、数据并行模型、异构多核并行模型、实时任务调度模型以及函数式并行模型。详细阐…...
VulkanSamples编译记录
按照BUILD.md说明,先安装依赖项 sudo apt-get install git build-essential libx11-xcb-dev \libxkbcommon-dev libwayland-dev libxrandr-dev 然后创建一个新文件夹build,在该目录下更新依赖项 cd VulkanSamples mkdir build cd build python ../scr…...
使用FabricJS对大图像应用滤镜(巨坑)
背景:我司在canvas的渲染模板的宽高都大于2048px 都几乎接近4000px,就导致使用FabricJS的滤镜功能图片显示异常 新知识:滤镜是对图片纹理的处理 FabricJS所能支持的最大图片纹理是2048的 一但图片超出2048的纹理尺寸 当应用滤镜时,图像会被剪切或者是缩…...
网页502 Bad Gateway nginx1.20.1报错与解决方法
目录 网页报错的原理 查到的502 Bad Gateway报错的原因 出现的问题和尝试解决 问题 解决 网页报错的原理 网页显示502 Bad Gateway 报错原理是用户访问服务器时,nginx代理服务器接收用户信息,但无法反馈给服务器,而出现的报错。 查到…...
Spring基础分析02-BeanFactory与ApplicationContext
大家好,今天和大家一起学习整理一下Spring 的BeanFactory和ApplicationContext内容和区别~ BeanFactory和ApplicationContext是Spring IoC容器的核心组件,负责管理应用程序中的Bean生命周期和配置。我们深入分析一下这两个接口的区别、使用场景及其提供…...
Rerender A Video 技术浅析(五):对象移除与自动配色
Rerender A Video 是一种基于深度学习和计算机视觉技术的视频处理工具,旨在通过智能算法对视频进行重新渲染和优化。 一、对象移除模块 1. 目标检测 1.1 概述 目标检测是对象移除的第一步,旨在识别视频中需要移除的对象并生成相应的掩码(m…...
Java项目实战II基于微信小程序的小区租拼车管理信息系统 (开发文档+数据库+源码)
目录 一、前言 二、技术介绍 三、系统实现 四、核心代码 五、源码获取 全栈码农以及毕业设计实战开发,CSDN平台Java领域新星创作者,专注于大学生项目实战开发、讲解和毕业答疑辅导。 一、前言 随着城市化进程的加速,小区居民对于出行方…...
【数字花园】数字花园(个人网站、博客)搭建经历汇总教程
目录 写在最最前面第一章:netlify免费搭建数字花园相关教程使用的平台步骤信息管理 第二章:本地部署数字花园数字花园网站本地手动部署方案1. 获取网站源码2.2 安装 Node.js 3. 项目部署3.1 安装项目依赖3.2 构建项目3.3 启动http服务器 4. 本地预览5. 在…...
WebRTC服务质量(03)- RTCP协议
一、前言: RTCP(RTP Control Protocol)是一种控制协议,与RTP(Real-time Transport Protocol)一起用于实时通信中的控制和反馈。RTCP负责监控和调节实时媒体流。通过不断交换RTCP信息,WebRTC应用…...
STM32F103单片机HAL库串口通信卡死问题解决方法
在上篇文章 STM32F103单片机使用STM32CubeMX创建IAR串口工程 中分享了使用cubeMX直接生成串口代码的方法,在测试的过程中无意间发现,串口会出现卡死的问题。 当串口一次性发送十几个数据的时候,串口感觉像卡死了一样,不再接收数据…...
Scala正则表达式
一、定义:正则表达式是一种用于匹配、查找和替换文本中特定模式的字符串。 使用方式:①定义一个正则 正则表达式应用场景:查找、验证、替换。 Ⅰ、查找 在目标字符串中,找到符合正则表达式规则要求的 子串。 方括号ÿ…...
每日一刷——二叉树的构建——12.12
第一题:最大二叉树 题目描述:654. 最大二叉树 - 力扣(LeetCode) 我的想法: 我感觉这个题目最开始大家都能想到的暴力做法就是遍历找到数组中的最大值,然后再遍历一遍,把在它左边的依次找到最大…...
Redis配置文件中 supervised指令
什么是Supervised? supervised模式允许Redis被外部进程管理器监控。通过这个选项,Redis能够在崩溃后自动重启,确保服务的高可用性。常见的进程管理器包括systemd和upstart。 开启方法 vim修改: sudo vi /etc/redis/redis.conf…...
OpenCV相机标定与3D重建(18)根据基础矩阵(Fundamental Matrix)校正两组匹配点函数correctMatches()的使用
操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 优化对应点的坐标。 cv::correctMatches 是 OpenCV 库中的一个函数,用于根据基础矩阵(Fundamental Matrix)校…...
pam_env.so模块配置解析
在PAM(Pluggable Authentication Modules)配置中, /etc/pam.d/su 文件相关配置含义如下: 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块,负责验证用户身份&am…...
论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)
笔记整理:刘治强,浙江大学硕士生,研究方向为知识图谱表示学习,大语言模型 论文链接:http://arxiv.org/abs/2407.16127 发表会议:ISWC 2024 1. 动机 传统的知识图谱补全(KGC)模型通过…...
使用Matplotlib创建炫酷的3D散点图:数据可视化的新维度
文章目录 基础实现代码代码解析进阶技巧1. 自定义点的大小和颜色2. 添加图例和样式美化3. 真实数据应用示例实用技巧与注意事项完整示例(带样式)应用场景在数据科学和可视化领域,三维图形能为我们提供更丰富的数据洞察。本文将手把手教你如何使用Python的Matplotlib库创建引…...
GruntJS-前端自动化任务运行器从入门到实战
Grunt 完全指南:从入门到实战 一、Grunt 是什么? Grunt是一个基于 Node.js 的前端自动化任务运行器,主要用于自动化执行项目开发中重复性高的任务,例如文件压缩、代码编译、语法检查、单元测试、文件合并等。通过配置简洁的任务…...
Python Ovito统计金刚石结构数量
大家好,我是小马老师。 本文介绍python ovito方法统计金刚石结构的方法。 Ovito Identify diamond structure命令可以识别和统计金刚石结构,但是无法直接输出结构的变化情况。 本文使用python调用ovito包的方法,可以持续统计各步的金刚石结构,具体代码如下: from ovito…...
MFC 抛体运动模拟:常见问题解决与界面美化
在 MFC 中开发抛体运动模拟程序时,我们常遇到 轨迹残留、无效刷新、视觉单调、物理逻辑瑕疵 等问题。本文将针对这些痛点,详细解析原因并提供解决方案,同时兼顾界面美化,让模拟效果更专业、更高效。 问题一:历史轨迹与小球残影残留 现象 小球运动后,历史位置的 “残影”…...
[免费]微信小程序问卷调查系统(SpringBoot后端+Vue管理端)【论文+源码+SQL脚本】
大家好,我是java1234_小锋老师,看到一个不错的微信小程序问卷调查系统(SpringBoot后端Vue管理端)【论文源码SQL脚本】,分享下哈。 项目视频演示 【免费】微信小程序问卷调查系统(SpringBoot后端Vue管理端) Java毕业设计_哔哩哔哩_bilibili 项…...
libfmt: 现代C++的格式化工具库介绍与酷炫功能
libfmt: 现代C的格式化工具库介绍与酷炫功能 libfmt 是一个开源的C格式化库,提供了高效、安全的文本格式化功能,是C20中引入的std::format的基础实现。它比传统的printf和iostream更安全、更灵活、性能更好。 基本介绍 主要特点 类型安全:…...
Python实现简单音频数据压缩与解压算法
Python实现简单音频数据压缩与解压算法 引言 在音频数据处理中,压缩算法是降低存储成本和传输效率的关键技术。Python作为一门灵活且功能强大的编程语言,提供了丰富的库和工具来实现音频数据的压缩与解压。本文将通过一个简单的音频数据压缩与解压算法…...
sshd代码修改banner
sshd服务连接之后会收到字符串: SSH-2.0-OpenSSH_9.5 容易被hacker识别此服务为sshd服务。 是否可以通过修改此banner达到让人无法识别此服务的目的呢? 不能。因为这是写的SSH的协议中的。 也就是协议规定了banner必须这么写。 SSH- 开头,…...
