2014-04-13 79 views
1

我的方法,進行上傳的圖像,我需要重命名它有固定名稱在我的應用程序但是,當使用File.Copy方法它返回結果(文件不存在) 我不知道那是怎麼回事如何在FileUpload控件Asp.net中重命名文件?

我試過這個File.Copy(UploadFile.FileName,newFilName); 也沒有響應

string filename = Path.GetFileName(FileUpload.FileName); 
       string extension = Path.GetExtension(FileUpload.PostedFile.FileName); 

       string oldFileName = FileUpload.FileName; 
       string newFileName = ("aboutusImage" + extension); 

       File.Copy(oldFileName, newFileName); 
       File.Delete(oldFileName); 

       File.Move(FileUpload.FileName, newFileName); 
       FileUpload.SaveAs(Server.MapPath("~/Styles/aboutusImages/") + newFileName); 

       var updateAboutus = (from a in dbContext.DynamicText 
            where a.Id == 1 
            select a).Single(); 
       updateAboutus.Id = updateAboutus.Id; 
       updateAboutus.Name = updateAboutus.Name; 
       updateAboutus.Image = Path.Combine("~/Styles/aboutusImages/", "aboutusImage.jpg"); 

       dbContext.SaveChanges(); 

回答

1

你正試圖從移動的名稱只是名稱這是在客戶端上給出的,而不是服務器上的當前名稱。它可能在服務器上的某個臨時位置。

您可能想要FileUpload.SaveAs函數。

2

FileUpload.FileName屬性表示客戶機上的文件名,而不是你的服務器上。 嘗試File.Copy就很少有可能成功,除非您在當前文件夾中的服務器中有相同的文件。

MSDN example

protected void UploadButton_Click(object sender, EventArgs e) 
{ 
    // Specify the path on the server to 
    // save the uploaded file to. 
    String savePath = @"c:\temp\uploads\"; 

    // Before attempting to perform operations 
    // on the file, verify that the FileUpload 
    // control contains a file. 
    if (FileUpload1.HasFile) 
    { 

     String fileName = FileUpload1.FileName; 

     // Append the name of the file to upload to the path. 
     savePath += fileName; 


     // Call the SaveAs method to save the 
     // uploaded file to the specified path. 
     // This example does not perform all 
     // the necessary error checking.    
     // If a file with the same name 
     // already exists in the specified path, 
     // the uploaded file overwrites it. 
     FileUpload1.SaveAs(savePath); 

當然,以下File.Delete,File.Move有同樣的問題,應予刪除