Best way to create a folder and upload a image to that folder in ASP.NET?


Question

Any code examples on how i must go about creating a folder say "pics" in my root and then upload a images from the file upload control in into that "pics" folder? If you don't want to give me all the code, i will be happy with a nice link also to show me how this will be done in VB.NET (C# is also ok).

1
3
4/8/2015 10:30:16 PM

Accepted Answer

Try/Catch is on you :)

public void EnsureDirectoriesExist()
        {

                // if the \pix directory doesn't exist - create it. 
                if (!System.IO.Directory.Exists(Server.MapPath(@"~/pix/")))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(@"~/pix/"));
                }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {


                if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
                {
                    // create posted file
                    // make sure we have a place for the file in the directory structure
                    EnsureDirectoriesExist();
                    String filePath = Server.MapPath(@"~/pix/" + FileUpload1.FileName);
                    FileUpload1.SaveAs(filePath);


                }
                else
                {
                    lblMessage.Text = "Not a jpg file";
                }


        }
13
4/11/2009 4:29:49 PM

here is how I would do this.

    protected void OnUpload_Click(object sender, EventArgs e)
    {
        var path = Server.MapPath("~/pics");
        var directory = new DirectoryInfo(path);

        if (directory.Exists == false)
        {
            directory.Create();
        }

        var file = Path.Combine(path, upload.FileName);

        upload.SaveAs(file);
    }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon