title: How to upload Word file in .NET core web API asynchronously and save into a folder
body: <p>I have written code for uploading the word file in .net core web api which is working fine synchronously but as this process taking time so success message is only coming once file is uploaded but I want to change that method asynchronously so that user does not have to wait for file upload and return message that &quot;This process will take some time&quot; and in background file upload should happen.It should not block the user to do not other operation due to file upload.</p>
  <p>Below I mention the code which I tried to work file upload asynchronously but it is not working.</p>
  <p>html and Javascript code-</p>
  <pre><code> &lt;button id=&quot;fake-file-button-browse&quot; type=&quot;button&quot; class=&quot;btn btn-default&quot; style=&quot;width:38px;height:34px;display:none&quot;&gt;&lt;/button&gt;
  &lt;input type=&quot;text&quot; id=&quot;fileurl-name&quot; style=&quot;width:50%;display:none&quot; placeholder=&quot;File not selected&quot; class=&quot;form-control&quot;&gt;
  &lt;input class=&quot;Uploader&quot; type=&quot;file&quot; id=&quot;fileurl&quot;&gt;
  </code></pre>
  <p>C# code, In Web API Controller</p>
  <pre><code>public async Task&lt;ActionResult&gt; UploadAndConvertFile()
  {
  
      try
      {
         
              List&lt;string&gt; listValues = new List&lt;string&gt;();
              foreach (string key in Request.Form.Keys)
              {
                  listValues.Add(Request.Form[key]);
              }
  
              List&lt;string&gt; details = new List&lt;string&gt;()
              {
                  listValues[0],listValues[2],listValues[5]
              };
              _response = _iOperation.GetAllFiles(details, CustomerId, &quot;Legal Team&quot;);
  
              if (_response.ResponseContent != &quot;Already Exist&quot; &amp;&amp; _response.StatusCode != 500)
              {
                  Operation.UploadedFileDetails uploadedFileDetails = new Operation.UploadedFileDetails();
  
                  uploadedFileDetails.CustomFileName = listValues[0];
                  uploadedFileDetails.FileDescriptions = listValues[1];
                  uploadedFileDetails.FileCategory = listValues[2];
                  uploadedFileDetails.IsActive = !Convert.ToBoolean(listValues[3]);
                  uploadedFileDetails.FileID = Convert.ToInt32(listValues[5]);
                  
                      
                      Microsoft.AspNetCore.Http.IFormFile file = Request.Form.Files[0];
                      System.Threading.Tasks.Task.Run(() =&gt; UploadFile(uploadedFileDetails,file));
                      
                      _response.StatusCode = 200;
                      _response.ResponseContent = &quot;File Upload will take some time.Please come after sometime.&quot;;
                      return StatusCode(Convert.ToInt16(_response.StatusCode), _response.ResponseContent);
  
  
  
                  
                  
  
              }
  
      } catch (Exception ex)
          {
              connection.fnHandleConnectionError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName.ToString() + &quot;.&quot; + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString(), connection.ConnectionString);
          }
          return StatusCode(Convert.ToInt16(_response.StatusCode), _response.ResponseContent);
      }
  
      public async Task&lt;Library.APIResponse&gt; UploadFile(UploadedFileDetails uploadedFileDetails, Microsoft.AspNetCore.Http.IFormFile File)
      {
          
          var file = File;
          object documentFormat = 8;
          string randomName = DateTime.Now.Ticks.ToString();
          string folderName = &quot;Uploads\\&quot;;
          string webRootPath = _hostingEnvironment.WebRootPath;
          string combinedPath = Path.Combine(webRootPath, folderName);
          object htmlFilePath = combinedPath + randomName + &quot;.htm&quot;;
          string directoryPath = combinedPath + randomName + &quot;_files&quot;;
          string fileSavePath = combinedPath + Path.GetFileName(file.FileName);
          object fileSavePath1 = combinedPath + Path.GetFileName(file.FileName);
          //If Directory not present, create it.
          if (!Directory.Exists(combinedPath))
          {
              Directory.CreateDirectory(combinedPath);
          }
          _Application applicationclass = new Application();
          //Upload the word document and save to Uploads folder.
  
          try
          {
              if (file.Length &gt; 0)
              {
                  
                  var filePath = Path.GetTempFileName();
  
                  using (var stream = System.IO.File.Create(filePath))
                  {
                      await file.CopyToAsync(stream);
                  }
                 
              }
              //Open the word document in background.
              applicationclass.Documents.Open(ref fileSavePath1);
              applicationclass.Visible = false;
              Document document = applicationclass.ActiveDocument;
              try
              {
                  //Save the word document as HTML file.
                  document.SaveAs(ref htmlFilePath, ref documentFormat);
  
                  //close the document
                  document.Close();
              }
              catch (Exception)
              {
                  document.Close();
                  throw;
              }
  
              //close the application
              applicationclass.Quit();
          }
          catch (Exception ex)
          {
              applicationclass.Quit();
              connection.fnHandleConnectionError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName.ToString() + &quot;.&quot; + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString(), connection.ConnectionString);
              throw;
          }
          //Read the saved Html File.
          string wordHTML =await System.IO.File.ReadAllTextAsync(htmlFilePath.ToString(), Encoding.Default);
  
          //Replace Image path
          wordHTML = wordHTML.Replace(&quot;src=\&quot;&quot;, &quot;src=\&quot;Uploads/&quot;);
  
          //Delete the Uploaded Word File.
          System.IO.File.Delete(fileSavePath.ToString());
  
          uploadedFileDetails.DocFileName = file.FileName;
          uploadedFileDetails.HTMLFileName = randomName + &quot;.htm&quot;;
          uploadedFileDetails.FileLocation = combinedPath;
          _response = await _iOperation.LogFileDetailsToDB(uploadedFileDetails); //This code to log to database the record
  
      return _response;
  }
  </code></pre>
  <p>First calling UploadAndConvertFile method which internally calling UploadFile method ,so first it should return mesaage that &quot;This file upload will take some time.&quot; , and in background it should call UploadFile method.</p>
  <p>It's calling UploadFile  method but when reaches to<br />
  <code>await file.CopyToAsync(stream);</code>
  This line it is going to catch block and throwing error &quot;Cannot access a disposed object.
  Object name: 'FileBufferingReadStream'.&quot;</p>
  <p>Thanks in advance.</p>