WebAPI 文件上传 MultipartFormDataStreamProvider 清理访问被拒绝

WebAPI File Upload MultipartFormDataStreamProvider cleanup access denied

我无法在用户上传文件后清理临时文件 多部分表单数据流提供者。我得到 "access to the path '...' is denied"。但是,它可以删除旧的临时文件。

我的清理基于此处给出的示例 MultipartFormDataStreamProvider Cleanup

我检查了 windows 身份,它具有对该文件夹的读取和Execute/read/write 访问权限。我想,文件以某种方式锁定了某些东西,但我不知道是什么。我尝试将删除移动到最后并添加睡眠,但都没有帮助。

清理这些文件的正确方法是什么?我需要在使用完文件后立即执行此操作。真的应该有一个设置,所以它会为你做。

    [HttpPost]
    [Route("UploadFile")]
    public async Task<HttpResponseMessage> UploadFile(string toolToken,
                                                       int Publication_ID,
                                                       string externalKey,
                                                       int dataTypeID,
                                                       int toolProject_ID,
                                                       string cngDesc)
    {
      Logger logger = LogManager.GetCurrentClassLogger();
      logger.Info("application pool user - " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
      try
      {
        string tempDir = Config.ServerTempDataDir; // is ~/App_Data";
        var provider = new MultipartFormDataStreamProvider(tempDir); //using this instead of ReadAsMultipartAsync because of memory constraints
        await Request.Content.ReadAsMultipartAsync(provider);
        MultipartFileData file = provider.FileData.FirstOrDefault(); //only one file is sent
        if (file != null)
        {
          var dir = Path.GetDirectoryName(file.LocalFileName);
          string begStr = Path.GetFileName(file.LocalFileName).Substring(0, 8);

          //will do something with file

          //delete file this fails every time, access denied
          try
          {
            File.Delete(file.LocalFileName);
          }
          catch (Exception e)
          {
            logger.Error("Cleanup Failed" + e.Message);
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
          }

          //delete any lingering files - this works
          foreach (var curFilePath in Directory.GetFiles(dir, begStr + "*")) 
          {
            if (File.GetCreationTime(curFilePath) < (DateTime.Now.AddHours(-3)))
            {
              try
              {
                File.Delete(curFilePath);
              }
              catch { }
            }
          }
        }

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"application/json");
        return response;
      }
      catch (Exception e)
      {
        logger.Error("Upload File Exception" + e.Message);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
      }

我们的网络人员对 App_Data 文件夹具有读取和Execute/read/write 访问权限,但没有 "modify" 访问权限。