使用新上传文件替换旧文件

时间:2014-03-13 09:32:22

标签: c# asp.net file file-upload

我正在创建一个Web应用程序,我必须使用fileupload上传的新文件替换现有的上传文件。

我正在使用以下代码:

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;
        }
    }

请更新代码以使用新上传的文件替换现有文件。

3 个答案:

答案 0 :(得分:4)

试试这个。

//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)));

答案 1 :(得分:1)

添加

File.Delete(Server.MapPath(Path.Combine("~/Data/", MyFile)));
在你的SaveAs电话会议之前

答案 2 :(得分:0)

试试这个:

 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));
    }
}