0

I have a controller method that works fine to upload images in Uploads folder. I try to create a date folder in it, so that I can group the images in relevant date folder. But Directory.CreateDirectory() is not creating a folder inside my existing Uploads Folder. I get an exception on SaveAs() method that

can't find the directory: MyApp/Uploads/10-11-2015

My Action Method

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ProductViewModel productViewModel)
        {
            var ValidImageTypes = new string[]{
                "image/gif",
                "image/jpeg",
                "image/jpg",
                "image/png"
            };

            if(!ValidImageTypes.Contains(productViewModel.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", "Please upload gif / jpg / png");
            }
            if (ModelState.IsValid)
            {
                var product = new Products
                {
                    Name = productViewModel.Name
                };

                var UploadDir = "/Uploads/" + DateTime.Now.ToString("dd/MM/yyyy") + "";
                var FolderUploadDir = DateTime.Now.ToString("dd/MM/yyyy");

                    Directory.CreateDirectory("~/Uploads/" + FolderUploadDir);

                //Saving the image
                productViewModel.ImageUpload.SaveAs(ImagePath);

            return View("Index");
            }
Muhammad Arslan Jamshaid
  • 1,077
  • 8
  • 27
  • 48

3 Answers3

3

You are using invalid date format string for file/folder name dd/MM/yyyy. Character " / " is not allowed in file/folder names. You may use dd-MM-yyyy instead

haraman
  • 2,744
  • 2
  • 27
  • 50
  • Additionally `/Uploads` and `~/Uploads` are not necessarily the same thing http://stackoverflow.com/questions/6424114/slash-vs-tilde-slash-in-style-sheet-path-in-asp-net – Eric J. Oct 11 '15 at 18:05
  • Yes, I basically used `/Uploads` to save it in database, because `~/Uploads` needs some trimming to remove `~` in order to show the image – Muhammad Arslan Jamshaid Oct 11 '15 at 18:26
1

I figured it out myself, I needed to provide a proper path of server to the CreateDirectory() method. Following code did the trick

var FolderUploadDir = Server.MapPath("~/Uploads/"+DateTime.Now.ToString("dd-MM-yyyy"));
Directory.CreateDirectory(FolderUploadDir);
Muhammad Arslan Jamshaid
  • 1,077
  • 8
  • 27
  • 48
0

Try using \\ in the directory address instead of /