views:

679

answers:

2

Hi

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).

Thanks in advanced!!!

+4  A: 

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";
                }


        }
roman m
+1 for the effort. In light of the recent discussions on over-engineering, I'm inclined to see the extraction of EnsureDirectoriesExist() as an example of unneeded abstraction. When you consider the context (a stackoverflow answer), I think it's safe to say, you ain't gonna need it.
harpo
thx, EnsureDirectoriesExist() can be used for other file system operations as well, not just for image uploads
roman m
A: 

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);
 }
Mike Geise