我正在创建一个应用程序,我给用户一些内存空间,我想计算他在文件夹中使用的总空间,并向他/她显示所用的总空间和可以使用的总剩余空间.如何计算整个文件夹的大小,包括c#中特定文件夹的所有文件.
您可以使用以下函数来计算特定文件夹的大小。
资料来源:https://askgif.com/blog/144/how-can-i-get-the-total-size-of-a-pspecial-folder-in-c/(礼貌:https://askgif.com / )
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];
}
Run Code Online (Sandbox Code Playgroud)
希望对你有帮助。
归档时间: |
|
查看次数: |
1611 次 |
最近记录: |