hi, i want the name of the image selected by a user when uploading an image to be changed to his username.
wrote this code but the image stored gets corrupt every time..
protected void Button1_Click(object sender, EventArgs e)
{
String imagefolder="images";
String path;
String savepath;
if (FileUpload1.HasFile)
{
path = Path.Combine(imagefolder, Request.PhysicalApplicationPath);
savepath = Path.Combine(path, User .Identity .Name .ToString ());
FileUpload1.SaveAs(savepath);
Label1.Text = "Done";
Response.Redirect("userprofile.aspx");
}
else
{
Label1.Text = "Select a file";
}
}
[]
Hi dear,
Your code is correct accept few problems related to it:
1. The code path = Path.Combine(imagefolder, Request.PhysicalApplicationPath); creates a wrong path, please chnage it code to
path = Path.Combine(Request.PhysicalApplicationPath, imagefolder);
2. The file name (Username in this case) is missing the extension, so when system try to save file it would generate errors.
3. Please check path should actually exist before you save file.
4. The username can have special charachers like '\' which need to be removed.
rest of your code is fine.
You can use following code for reference
protected void Button1_Click(object sender, EventArgs e)
{
String imagefolder = "images";
String path;
String savepath;
if (FileUpload1.HasFile)
{
path = Path.Combine(Request.PhysicalApplicationPath, imagefolder);
if (Directory.Exists(path))
{
savepath = Path.Combine(path, User.Identity.Name.ToString().Replace(@"\", "_") + "__" + Path.GetFileName(FileUpload1.FileName.ToString()));
FileUpload1.SaveAs(savepath);
Label1.Text = "Done";
Response.Redirect("userprofile.aspx");
}
else
{
Label1.Text = "Error: file path do not exist";
}
}
else
{
Label1.Text = "Select a file";
}
}