删除用户文件夹文件时误删UploadedFilesForEncrypting目录问题
问题:误删目录而非仅删除目录内文件
处理仓库文件夹中的文件与目录时出现异常:原本只想删除指定文件夹内的文件,却误删了UploadedFilesForEncrypting目录本身。
用户共享文件夹字段定义
public string FolderForEnc { get { return Path.Join(_webHostEnvironment.WebRootPath, "UploadedFilesForEncrypting"); } }
实现用户文件夹文件删除逻辑的控制器代码
[HttpDelete("DeleteEncryptedFiles")] public IActionResult DeleteFiles([FromHeader(Name = "ApiKey")] string apiKey) { try { // 此处验证API密钥有效性并进行用户授权 var userid = "air"; //_readUser.ReadUserIdByApiKey(apiKey) string uploadsFolder = Path.Join(FolderForEnc, $"User({userid})"); if (Directory.Exists(uploadsFolder)) { string[] uploadedFiles = Directory.GetFiles(uploadsFolder); if(uploadedFiles.Length > 0) { foreach (string filePath in uploadedFiles) { System.IO.File.Delete(filePath); } return Ok(new { message = "Files deleted successfully" }); } return NotFound("There are no files in your folder"); } else { return NotFound("User folder not found"); } } catch (InvalidOperationException) { return BadRequest("User with this API key not found"); } catch (Exception ex) { return BadRequest(ex.Message); } }
已尝试以下操作,均未解决问题:
- 将
Path.Join改为Path.Combine - 修改
Directory.GetFiles为Directory.GetFiles(uploadsFolder, "*", SearchOption.AllDirectories) - 传入抽象数据
内容的提问来源于stack exchange,提问作者user21458603
相关产品推荐
相关产品推荐

