Unable to save the image into the directory in my project solution

-3

This function is called when user click the submit button and it would save the image into my project directory and the filename into SQL database. I currently having problem that when i run the project it would not work. How i can fix my code? Any help will be very appreciated thanks.

private Product CreateProduct()
{
    Product product = new Product();
    string filename = Path.GetFileName(FileUpload1.FileName);
    product.Name = txtName.Text;
    product.Price = Convert.ToInt32(txtPrice.Text);
    product.TypeID = Convert.ToInt32(ddltype.SelectedValue);
    product.Description = txtDescription.Text;
    if (FileUpload1.HasFile)
    {
        FileUpload1.SaveAs(Server.MapPath("~/Images/Products/") + filename);
    }
    product.Image = FileUpload1.FileName;

    return product;
}

UPDATED : The error is System.IO.DirectoryNotFoundException
HResult=0x80070003 Message=Could not find a part of the path 'C:\Users\user\source\repos\FYP\FYP\Images\Products\testing.png'.
Source= StackTrace:

c#
asp.net
image-uploading
asked on Stack Overflow Aug 12, 2019 by Roxas • edited Aug 12, 2019 by Sunil Dhappadhule

1 Answer

0

code does not get Products directory, first check Products directory exists or not if no exists then create directory check code below,

private Product CreateProduct()
{
    Product product = new Product();
    string filename = Path.GetFileName(FileUpload1.FileName);
    product.Name = txtName.Text;
    product.Price = Convert.ToInt32(txtPrice.Text);
    product.TypeID = Convert.ToInt32(ddltype.SelectedValue);
    product.Description = txtDescription.Text;
 bool exists = System.IO.Directory.Exists(Server.MapPath("~/Images/Products/"));
            if (!exists)
                System.IO.Directory.CreateDirectory(Server.MapPath("~/Images/Products/"));
    if (FileUpload1.HasFile)
    {
        FileUpload1.SaveAs(Server.MapPath("~/Images/Products/") + filename);
    }
    product.Image = FileUpload1.FileName;

    return product;
}
answered on Stack Overflow Aug 12, 2019 by Sanjay Bharga

User contributions licensed under CC BY-SA 3.0