C# 文件移动、删除
文件移动 ----
将文件从文件夹A移动到文件夹B并按规则重命名
// <summary> /// 将文件移动到指定目录 /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param> /// <param name="descDirectoryPath">移动到的目录的路径</param> /// <param name="newFileName">移动到的目录后的新文件名</param> ///</summary> public static string Move(string sourceFilePath, string descDirectoryPath,string newFileName) { //获取源文件的扩展名 string sourceExtFileName = Path.GetExtension(sourceFilePath); if (!Directory.Exists(descDirectoryPath)) { Directory.CreateDirectory(descDirectoryPath); //如果目标中存在同名文件,则删除 } if (File.Exists(descDirectoryPath + "\\" + newFileName + sourceExtFileName)) { File.Delete(descDirectoryPath + "\\" + newFileName + sourceExtFileName); } //将文件移动到指定目录 string newFilePath = descDirectoryPath + "\\" + newFileName + sourceExtFileName; File.Move(sourceFilePath, newFilePath); return newFilePath; }
搭配使用_生成6位随机数字
Random random = new Random(); int randomNumber = random.Next(1, 10) * 100000 + random.Next(0, 100000); string code = randomNumber.ToString("D6");
测试案例:
sourceFilePath --- D:\PRO\YHQWebManagement\Admin.NET.Web.Entry\\uploads\OrgLicenceImgTest\13602295957573.jpg
descDirectoryPath --- uploads\OrgLicenceImg
newFileName --- 756813
-----------------------------------------------------------------------
newFilePath ---- uploads\OrgLicenceImg\756813.jpg
文件删除 ----
/// <summary> /// 删除文件 /// </summary> /// <param name="filePath">全路径 绝对路径</param> /// <returns></returns> public async Task DeleteFileByPath(string filePath) { if (File.Exists(filePath)) { File.Delete(filePath); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界