2012-07-30 67 views
0

在我的asp mvc 3應用程序中,我有一個允許用戶下載給定文件的動作。如何計算C#中的文件大小

下面是代碼:

public FilePathResult DownloadFile(string fileName) 
    { 
     try 
     { 
      string uploadsDocumentPath = System.Configuration.ConfigurationManager.AppSettings["uploadsDocumentPath"].ToString(); 
      string ext = Path.GetExtension(fileName).ToLower(); 
      Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); // henter info fra windows registry 
      if (regKey != null && regKey.GetValue("Content Type") != null) 
      { 
       mimeType = regKey.GetValue("Content Type").ToString(); 
      } 

      return File(uploadsDocumentPath + fileName, mimeType, fileName); 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
    } 

我希望能夠允許尺寸小於要下載150MB僅文件。但我找不到如何計算這種類型的文件的大小。

任何想法?

回答

3

我想這應該工作:

FileInfo file = new FileInfo(uploadsDocumentPath + fileName); 
if(file.Length > 157286400) 
{ 
     // Return error here. 
} 
+0

工作就像一個魅力,謝謝。 – kbaccouche 2012-07-30 13:29:26

+0

沒問題!很高興我可以幫助:) – 2012-07-30 13:29:56

+2

150000000不是150MB。 157286400是150MB = 1024x1024 x150 – 2012-07-30 13:48:02