2014-01-29 74 views
4

我創建了一個應用程序,爲用戶提供了一定的內存空間,我希望 可以計算他在文件夾中使用的總空間,並向他/她顯示所使用的總空間以及可用的總剩餘空間。 如何計算整個文件夾的大小,包括c#中特定文件夾的所有文件。如何獲得C#中特定文件夾的總大小?

回答

2

您可以使用下面的函數來計算特定文件夾的大小。

static String GetDriveSize(String ParticularFolder, String drive) 
    { 
     String size = ""; 
     long MaxSpace = 10485760; 
     String rootfoldersize = @"~/userspace/" + ParticularFolder+ "/"; 
     long totalbytes = 0; 
     long percentageusage = 0; 

     totalbytes = GetFolderSize(System.Web.HttpContext.Current.Server.MapPath(rootfoldersize) + "" + drive + "/"); 
     percentageusage = (totalbytes * 100)/MaxSpace; 
     size = BytesToString(totalbytes); 

     return size; 
    } 

static long GetFolderSize(string s) 
    { 
     string[] fileNames = Directory.GetFiles(s, "*.*"); 
     long size = 0; 

     // Calculate total size by looping through files in the folder and totalling their sizes 
     foreach (string name in fileNames) 
     { 
      // length of each file. 
      FileInfo details = new FileInfo(name); 
      size += details.Length; 
     } 
     return size; 
    } 

static String BytesToString(long byteCount) 
    { 
     string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB 
     if (byteCount == 0) 
      return "0" + suf[0]; 
     long bytes = Math.Abs(byteCount); 
     int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); 
     double num = Math.Round(bytes/Math.Pow(1024, place), 1); 
     return (Math.Sign(byteCount) * num).ToString() + suf[place]; 
    } 

希望這會對你有幫助。

2

您可以使用DirectoryInfo.GetFilesFileInfo.Length

DirectoryInfo dir = new DirectoryInfo(@"D:\Data\User_ABC"); 
FileInfo[] files = dir.GetFiles(); 
long totalByteSize = files.Sum(f => f.Length); 

如果您還希望包括子sirectories:

FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories); 
1
using System; 
using System.IO; 

class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine(GetDirectorySize("C:\\Site\\")); 
    } 

    static long GetDirectorySize(string p) 
    { 
     // 1. 
     // Get array of all file names. 
     string[] a = Directory.GetFiles(p, "*.*"); 

     // 2. 
     // Calculate total bytes of all files in a loop. 
     long b = 0; 
     foreach (string name in a) 
     { 
      // 3. 
      // Use FileInfo to get length of each file. 
      FileInfo info = new FileInfo(name); 
      b += info.Length; 
     } 
     // 4. 
     // Return total size 
     return b; 
     } 
} 
相關問題