Create new directory according to string

0

I have a function that saves an image to a standard directory for all companies, and I tried to change it to save to a directory according to this companyFolder string I created. But this is not getting saved.

How can I do this?

[HttpPost]
public JsonResult StoreImage(int idCompany)
{
    try
    {
        var companyFolder = idCompany.ToString(); 
        System.IO.Directory.CreateDirectory(Server.MapPath(companyFolder)); //creates new directory
        int numFiles = 0; //numero de imagens no diretorio da empresa

        var file = Request.Files["UploadFile"]; //arquivo que foi enviado para upload
        if ((file != null) && (file.ContentLength > 0)) //adicionar verificaçao de quantidade de imagens (para limitar a 5)
        {
            string fn = Path.GetFileName(file.FileName); //obtem nome do arquivo
            var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Content/img/upload_empresa/" + companyFolder + "/")); //diretorio onde o arquivo vai ser salvo
            //var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Content/img/upload_empresa/" + companyFolder));
            FileInfo[] existingImage = dir.GetFiles("imd_" + idCompany + "_*.*");

            string SaveLocation = Server.MapPath("~/Content/img/upload_empresa/" + companyFolder + "/imd_" + idCompany + "_" + existingImage.Length + Path.GetExtension(fn));

            try
            {
                file.SaveAs(SaveLocation);
            }
            catch
            {
                return Json(new { success = "false", message = "erro" });
            }
        }
    }
}

Edit: I have now seen in the console that the following exception is generated:

  

Exception Generated: 'System.IO.DirectoryNotFoundException' in mscorlib.dll

    
asked by anonymous 18.12.2018 / 12:19

1 answer

1

Verify that the directory you are trying to save the image exists in:

if (!System.IO.Directory.Exists(SaveLocation))
  System.IO.Directory.CreateDirectory(SaveLocation)

file.SaveAs(SaveLocation);
    
18.12.2018 / 12:33