2014-01-12 59 views
0

嗨我使用這個工具,使文件上傳和刪除上傳。 MVC 4 LINQ to SQL。上傳文件,檢查相同的文件名

我想檢查一下文件是否已經上傳,如果發送消息 嘗試新文件。

你能幫我,開始,爲此添加代碼嗎?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.IO; 


namespace CFire2.SupplyConUtils 

{ 
public static class FileUpload 
{ 

    public static char DirSeparator = 
    System.IO.Path.DirectorySeparatorChar; 
    public static string FilesPath = "Content" + 
    DirSeparator + "SupplyUpload" + DirSeparator; 

    public static string UploadFile(HttpPostedFileBase file) 
    { 
     // Check if we have a file 
     if (null == file) return ""; 
     // Make sure the file has content 
     if (!(file.ContentLength > 0)) return ""; 

     string fileName = file.FileName; 
     string fileExt = Path.GetExtension(file.FileName); 

     // Make sure we were able to determine a proper 
     // extension 
     if (null == fileExt) return ""; 

     // Check if the directory we are saving to exists 
     if (!Directory.Exists(FilesPath)) 
     { 
      // If it doesn't exist, create the directory 
      Directory.CreateDirectory(FilesPath); 
     } 

     //// Set our full path for saving 
     var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName); 


     // Save our file 


     file.SaveAs(path); 

     // Return the filename 
     return fileName; 


    } 
    public static void DeleteFile(string fileName) 
    { 
     // Don't do anything if there is no name 
     if (fileName.Length == 0) return; 

     // Set our full path for deleting 
     var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName); 


     // Check if our file exists 

      if (File.Exists(path)) 
     { 
      // Delete our file 

      File.Delete(path); 
     } 
    } 
} 

}

回答

0

MSDN文檔爲HttpPostedFileBase.FileName

當在派生類中重寫時,獲取的 完全合格的名稱在客戶端上的文件。

所以可能你需要添加此行以正確執行您的支票

string fileName = Path.GetFileName(file.FileName); 

然後

var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), 
                   fileName); 
    if(File.Exists(path)) 
     return "The file has been already uploaded! 
    .... 
+0

HEJ史蒂夫運行完美TKS。 – user3062392