Reputation: 1046
I'm creating a web application in which I have to replace the existed uploaded file with the new file uploaded by the fileupload
.
I'm using the following code:
void UploadFile()
{
HttpPostedFile PostedFile = Request.Files["FileUploadExcel"];
if (PostedFile != null && PostedFile.ContentLength > 0)
{
MyFile = Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Data/", MyFile)));
Get_Data(MyFile);
}
else
{
LblMessage.Text = "Missing File";
LblMessage.Visible = true;
}
}
Please update the code to replace the existing file with the newly uploaded file.
Upvotes: 0
Views: 9070
Reputation: 1
Try this one:
if (FLUpload.PostedFile != null && FLUpload.PostedFile.FileName != "")
{
if (System.IO.Directory.Exists(Server.MapPath("~/Files/")) == false)
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Files/"));
System.IO.Directory.Delete(Server.MapPath("~/Files/") + path);
}
else
{
FLUpload.SaveAs(Server.MapPath(path));
}
}
Upvotes: 0
Reputation: 7525
try this.
//determine if file exist
If(File.Exists(Server.MapPath(Path.Combine("~/Data/", MyFile))))
{
//delete existing file
File.Delete(Server.MapPath(Path.Combine("~/Data/", MyFile)));
}
PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Data/", MyFile)));
Upvotes: 4
Reputation: 12807
Just add
File.Delete(Server.MapPath(Path.Combine("~/Data/", MyFile)));
before your SaveAs call.
Upvotes: 1