Best way to create a folder and upload a image to that folder in ASP.NET?
28,871
Solution 1
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";
}
}
Solution 2
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);
}
Author by
Etienne
Updated on July 27, 2022Comments
-
Etienne almost 2 years
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).