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

Any code examples on how I need to create a folder will say β€œpics” in my root, and then upload the images from the file upload control to the β€œpics” folder? If you do not want to give me all the code, I will be happy with a good link to show me how this will be done in VB.NET (C # is also ok).

+3
source share
3 answers

Try / catch 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
source

this is how i do it.

    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);
    }
+2
source

    DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/FolderName/") + txtNewmrNo.Text)); //Creating SubFolder inside the Folder with Name(which is provide by User).
    string directoryPath = info+"/".ToString();
    if (!info.Exists)  //Checking If Not Exist.
    {
        info.Create();
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++) //Checking how many files in File Upload control.
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                hpf.SaveAs(directoryPath + Path.GetFileName(hpf.FileName)); //Uploading Multiple Files into newly created Folder (One by One).
            }
        }
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This Folder already Created.');", true);
    }
0

Source: https://habr.com/ru/post/1706275/


All Articles