Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
HttpContext.Current is null


What I have tried:

public async Task<ActionResult> UploadZipedDocumentFile()
      {
          try
          {
              if (Request.Files["fileUploadUpdateDocument"].ContentLength > 0 && Request.Files["fileUploadUpdateDocument"].ContentLength < Convert.ToInt64(WebConfigurationManager.AppSettings["UploadDataLength"]))
              {
                  string zipFileSavePath = string.Empty;
                  string zipExtractPath = string.Empty;
                  string directory = string.Empty;
                  string fullfilepath = string.Empty;
                  string filePath = string.Empty;
                  var Targetfile = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["CandidateFileUploadLocation"]);
                  var TargetPath = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["CandidateFileUploadLocation"]);
          string zipFileName = Request.Files["fileUploadUpdateDocument"].FileName;
                  string fileExtension = System.IO.Path.GetExtension(Request.Files["fileUploadUpdateDocument"].FileName);
                  string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(Request.Files["fileUploadUpdateDocument"].FileName);
                  if (fileExtension == ".zip")
                  {
                      zipFileSavePath =  System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["ZipFileUploadLocation"] + CommonFuntion.GenerateFileKey(zipFileName) + fileExtension);
                      Request.Files["fileUploadUpdateDocument"].SaveAs(zipFileSavePath);
                      zipExtractPath = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"]);// + fileNameWithoutExtension);
                      ZipFile.ExtractToDirectory(zipFileSavePath, zipExtractPath);
                      filePath = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"] + fileNameWithoutExtension);
                      List<string> listOfpassportnumbers = new List<string>();
                      try
                      {
                          foreach (string item in Directory.GetDirectories(filePath))
                          {
                              var stringCutted = item.Split('\\').Last();
                              listOfpassportnumbers.Add(stringCutted);
                          }
                      }
                      catch
                      {
                          fullfilepath = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"]);
                          System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
                          deleteTheseFiles.Delete(true);
                          TempData["ErrorMessages"] = @Mui.structureNotCorrectMessage;
                          TempData["ErrorText"] = "false";
                          return RedirectToAction("Index", "CSR");
                      }

                      List<FileUpload> lstUploadedFiles = new List<FileUpload>();
                      var listOfDefaultyPassportNumber = new StringBuilder();
                      if (listOfpassportnumbers != null)
                      {



                          await Task.Run(() =>
                           {

                               foreach (var item in listOfpassportnumbers)
                               {
                                   var checkCandidateExist = service.GetAll().Where(x => x.IsDeleted == false && x.PassPortNo == item).FirstOrDefault();
                                   if (checkCandidateExist != null)
                                   {
                                       directory = zipExtractPath + fileNameWithoutExtension + "\\" + item;//System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"] + fileNameWithoutExtension + "\\" + item);
                                       var checkAnyFolderExist = 0;
                                       // Visa documents upload process
                                       // var section = (Hashtable)ConfigurationManager.GetSection("MobolizationDocumentType");//remove
                                       Dictionary<Int32, string> dictionary = new Dictionary<Int32, string>(); //section.Cast<DictionaryEntry>().ToDictionary(d => Convert.ToInt32(d.Value), d => Convert.ToString(d.Key));
                                       dictionary.Add(3, "Visa");
                                       dictionary.Add(7, "VAD");
                                       dictionary.Add(4, "Medical");
                                       dictionary.Add(5, "Imigiration");
                                       dictionary.Add(9, "Insurance");
                                       dictionary.Add(15, "Ticket");
                                       dictionary.Add(16, "Dispatch");
                                       dictionary.Add(6, "OfferLetter");
                                       foreach (KeyValuePair<Int32, string> kVp in dictionary)
                                       {
                                           var filepath = directory + "\\" + Convert.ToString(kVp.Value);

                                           if (System.IO.Directory.Exists(filepath))
                                           {
                                               string sourcefile = Targetfile;
                                               string destinationpath = TargetPath;
                                               var VisaDocs = System.IO.Directory.GetFiles(filepath).ToList();
                                               foreach (var VisaDoc in VisaDocs)
                                               {
                                                   FileUpload objFileUpload = new FileUpload();
                                                   objFileUpload.DocTypeId = Convert.ToInt32(kVp.Key);
                                                   objFileUpload.DocType = Convert.ToString(kVp.Value);
                                                   objFileUpload.DocExtension = VisaDoc.Substring(VisaDoc.LastIndexOf(".") + 0);
                                                   objFileUpload.DocFileName = CommonFuntion.GenerateFileKey(VisaDoc);
                                                   objFileUpload.FileName = Path.GetFileName(VisaDoc);
                                                   lstUploadedFiles.Add(objFileUpload);
                                                   sourcefile = Path.Combine(Targetfile + objFileUpload.DocType, objFileUpload.DocFileName + objFileUpload.DocExtension);
                                                   destinationpath = destinationpath + objFileUpload.DocType;
                                                   if (!System.IO.Directory.Exists(destinationpath))
                                                   {
                                                       System.IO.Directory.CreateDirectory(destinationpath);
                                                   }
                                                   System.IO.File.Copy(VisaDoc, sourcefile);

                                                   var candidateDocument = new CandidateDocument();
                                                   candidateDocument.CandidateId = Convert.ToInt64(checkCandidateExist.Id);
                                                   candidateDocument.DocTypeId = objFileUpload.DocTypeId;
                                                   candidateDocument.DocType = objFileUpload.DocType;
                                                   candidateDocument.FileName = objFileUpload.FileName;
                                                   candidateDocument.DocFileName = objFileUpload.DocFileName;
                                                   candidateDocument.DocExtension = objFileUpload.DocExtension;
                                                   candidateDocument.CreatedBy = SessionWrapper.User.Id;
                                                   candidateDocument.CreatedDate = DateTime.Now;
                                                   candidateDocument.UpdatedBy = SessionWrapper.User.Id;
                                                   candidateDocument.UpdatedDate = DateTime.Now;
                                                   canDocumentService.Create(candidateDocument);
                                                   canDocumentService.Save();
                                                   lstUploadedFiles.Clear();
                                               }
                                           }
                                           else
                                           {
                                               checkAnyFolderExist++;
                                           }
                                       }

                                   }
                                   else
                                   {
                                       listOfDefaultyPassportNumber.Append(item + ',');
                                   }
                               }

                           });
                          //xy = System.Web.HttpContext.Current;
                          //if (xy == null)
                          //{
                          //    // thrown
                          //    throw new ArgumentException("HttpContext.Current is null");
                          //}
                          fullfilepath = System.Web.HttpContext.Current.Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"] + "\\" + fileNameWithoutExtension);
                          System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
                          deleteTheseFiles.Delete(true);
                          string defaultyPassportNumber = listOfDefaultyPassportNumber.ToString().TrimEnd(',');
                          if (defaultyPassportNumber != string.Empty)
                          {
                              TempData["ErrorMessages"] = @Mui.passportNoNotFound + " " + defaultyPassportNumber + " " + @Mui.notUploadMessage;
                              TempData["ErrorText"] = "false";
                              return RedirectToAction("Index", "CSR");
                          }
                          else
                          {
                              TempData["ErrorText"] = "True";
                              return RedirectToAction("Index", "CSR");
                          }
                      }
                      else
                      {
                          //fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"] + "\\" + fileNameWithoutExtension);
                          //System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
                          //deleteTheseFiles.Delete(true);
                          TempData["ErrorMessages"] = @Mui.documentEmptyMessage;
                          TempData["ErrorText"] = "false";
                          return RedirectToAction("Index", "CSR");
                      }

                  }
                  else
                  {
                      TempData["ErrorMessages"] = @Mui.formatNotSupportedMessage;
                      TempData["ErrorText"] = "false";
                      return RedirectToAction("Index", "CSR");
                  }
              }
              else
              {
                  TempData["ErrorMessages"] = @Mui.selectFileUploadMessage;
                  TempData["ErrorText"] = "false";
                  return RedirectToAction("Index", "CSR");
              }

          }
          catch (Exception ex)
          {
              //x = HttpContext.Current;
              //if (x == null)
              //{
              //    // thrown
              //    throw new ArgumentException("HttpContext.Current is null");
              //}
              log.Error(ex.StackTrace);
              if (ex.Message.Contains("Maximum request length exceeded"))
              {
                  TempData["ErrorException"] = ex.Message;
                  TempData["ErrorText"] = "false";

                  return RedirectToAction("Index", "CSR");
              }

              return RedirectToAction("Index", "CSR");
          }


      }
Posted
Comments
Kornfeld Eliyahu Peter 13-Jun-17 7:33am    
And if you try HttpContext.Current only (without the 'System.Web.' prefix)?
Richard Deeming 13-Jun-17 9:39am    
Try replacing System.Web.HttpContext.Current.Server.MapPath with System.Web.Hosting.HostingEnvironment.MapPath - assuming you're not using a relative path, that will return the same value.
prakash00060 14-Jun-17 3:46am    
problem is same

In await method Httpcontext.current became null and my program is break.
Richard Deeming 14-Jun-17 5:43am    
If you use HostingEnvironment.MapPath, you don't need HttpContext.Current. As far as I can see, you're not using it for anything else.
prakash00060 14-Jun-17 9:40am    
sir problem is same
In await method Httpcontext.current became null and my program is break.

public async Task<actionresult> UploadZipedDocumentFile()
{
try
{
if (Request.Files["fileUploadUpdateDocument"].ContentLength > 0 && Request.Files["fileUploadUpdateDocument"].ContentLength < Convert.ToInt64(WebConfigurationManager.AppSettings["UploadDataLength"]))
{
string zipFileSavePath = string.Empty;
string zipExtractPath = string.Empty;
string directory = string.Empty;
string fullfilepath = string.Empty;
string filePath = string.Empty;
//HttpContext ctx = System.Web.HttpContext.Current;
string zipFileName = Request.Files["fileUploadUpdateDocument"].FileName;
string fileExtension = System.IO.Path.GetExtension(Request.Files["fileUploadUpdateDocument"].FileName);
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(Request.Files["fileUploadUpdateDocument"].FileName);
if (fileExtension == ".zip")
{
zipFileSavePath = HostingEnvironment.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["ZipFileUploadLocation"] + CommonFuntion.GenerateFileKey(zipFileName) + fileExtension);
Request.Files["fileUploadUpdateDocument"].SaveAs(zipFileSavePath);
zipExtractPath = HostingEnvironment.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"]);// + fileNameWithoutExtension);
ZipFile.ExtractToDirectory(zipFileSavePath, zipExtractPath);
filePath = HostingEnvironment.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"] + fileNameWithoutExtension);
List<string> listOfpassportnumbers = new List<string>();
try
{
foreach (string item in Directory.GetDirectories(filePath))
{
var stringCutted = item.Split('\\').Last();
listOfpassportnumbers.Add(stringCutted);
}
}
catch
{
fullfilepath = HostingEnvironment.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["UnZipFileUploadLocation"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
TempData["ErrorMessages"] = @Mui.structureNotCorrectMessage;
TempData["ErrorText"] = "false";
return RedirectToAction("Index", "CSR");
}

List<fileupload> lstUploadedFiles = new List<fileupload>();
var listOfDefaultyPassportNumber = new StringBuilder();
if (listOfpassportnumbers != null)
{
await Task.Run(() =>
{
//System.Web.HttpContext.Current = ctx;
foreach (var item in listOfpassportnumbers)
{
var checkCandidateExist = service.GetAll().Where(x => x.IsDeleted == false && x.PassPortNo == item).FirstOrDefault();
if (checkCandidateExist != null)
{
d

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900