Nimit Joshi
Nimit Joshi

Reputation: 1046

Replace Old FIle with the New upload File

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

Answers (3)

user8996570
user8996570

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

Ashwini Verma
Ashwini Verma

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

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

Just add

File.Delete(Server.MapPath(Path.Combine("~/Data/", MyFile)));

before your SaveAs call.

Upvotes: 1

Related Questions