Create new directory according to string

Asked

Viewed 112 times

0

I have a function that saves an image in a default directory, for all companies, and I tried to change this to save in a directory according to this string companyFolderwhich I have created. Yet you are not being saved.

How can I do that?

[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: vi agora no console que é gera a seguinte exception:

Exception generated: 'System.IO.Directorynotfoundexception' in mscorlib.dll

  • I was able to create, I found that there in System.IO.Directory.Createdirectory(Server.Mappath(companyFolder)); it is necessary to pass all the way, and not only the name of the folder to be created

1 answer

0

Check if the directory that is trying to save the image exists:

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

file.SaveAs(SaveLocation);
  • it is not necessary to check if it exists, if it does not exist it creates the directory

Browser other questions tagged

You are not signed in. Login or sign up in order to post.