我已编写以下例程来手动遍历目录并在C#/ .NET中计算其大小:
protected static float CalculateFolderSize(string folder)
{
float folderSize = 0.0f;
try
{
//Checks if the path is valid or not
if (!Directory.Exists(folder))
return folderSize;
else
{
try
{
foreach (string file in Directory.GetFiles(folder))
{
if (File.Exists(file))
{
FileInfo finfo = new FileInfo(file);
folderSize += finfo.Length;
}
}
foreach (string dir in Directory.GetDirectories(folder))
folderSize += CalculateFolderSize(dir);
}
catch (NotSupportedException e)
{
Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
}
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("Unable to calculate folder …
Run Code Online (Sandbox Code Playgroud) 我想使用python快速找到任何文件夹的总大小.
import os
from os.path import join, getsize, isfile, isdir, splitext
def GetFolderSize(path):
TotalSize = 0
for item in os.walk(path):
for file in item[2]:
try:
TotalSize = TotalSize + getsize(join(item[0], file))
except:
print("error with file: " + join(item[0], file))
return TotalSize
print(float(GetFolderSize("C:\\")) /1024 /1024 /1024)
Run Code Online (Sandbox Code Playgroud)
这是我编写的简单脚本来获取文件夹的总大小,花了大约60秒(+ -5秒).通过使用多处理,我在四核机器上将其降低到23秒.
使用Windows文件浏览器只需约3秒钟(右键单击 - >属性可自行查看).那么是否有更快的方法来查找接近Windows可以执行的速度的文件夹的总大小?
Windows 7,python 2.6(搜索但是大多数时候人们使用了与我自己非常相似的方法)在此先感谢.