You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

删除用户文件夹文件时误删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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:23:17