Below is a complete C# example showing how to save an uploaded image to a folder using FormCollection in an ASP.NET MVC controller. This includes:

  • Creating the directory if it doesn't exist

  • Checking if a file with the same name already exists

  • Deleting the old file if found

  • Saving the new file


đŸ’» C# Code (Controller)

    [HttpPost]
    public ActionResult UploadImage(FormCollection form)
    {
        // Assuming your file input name in the form is "imageFile"
        HttpPostedFileBase file = Request.Files["imageFile"];

        if (file != null && file.ContentLength > 0)
        {
            string fileName = Path.GetFileName(file.FileName);
            string folderPath = Server.MapPath("~/UploadedImages"); // You can change the path
            string fullPath = Path.Combine(folderPath, fileName);

            // Create the directory if it doesn't exist
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            // Check if the file already exists, and delete it
            if (System.IO.File.Exists(fullPath))
            {
                System.IO.File.Delete(fullPath);
            }

            // Save the new file
            file.SaveAs(fullPath);

            ViewBag.Message = "Image uploaded successfully.";
        }
        else
        {
            ViewBag.Message = "Please select a valid image file.";
        }

        return View();
    }


📝 HTML View Example
using (Html.BeginForm("UploadImage", "YourControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="imageFile" />
        <input type="submit" value="Upload Image" />
        <p>@ViewBag.Message</p>
    }


📁 Notes

  • ~/UploadedImages is the folder where images will be stored inside your project directory.

  • Make sure the folder you're writing to has write permissions, especially on a production server.

  • This code works with standard form submissions, not AJAX. If you're using AJAX or APIs, the logic will be slightly different.

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions