日期:2014-05-19  浏览次数:20798 次

如何获取一个文件夹的大小
Directory.GetFileSystemEntries
File.Exists()
基本思想是通过上面的两个方法进行递归,进而求取文件夹中所有文件大小的总和,可是小弟数据结构实在是太烂,不知道在递归的时候如何取值,做什么样的运算.
希望各位朋友能够指点一二,谢谢

------解决方案--------------------
public static long DirSize(DirectoryInfo d)
{
long Size = 0;
// Add file sizes.
FileInfo[] fis = d.GetFiles();
foreach (FileInfo fi in fis)
{
Size += fi.Length;
}
// Add subdirectory sizes.
DirectoryInfo[] dis = d.GetDirectories();
foreach (DirectoryInfo di in dis)
{
Size += DirSize(di);
}
return(Size);
}
------解决方案--------------------
public long DirectorySize(string strDirectory)
{
if (!Directory.Exists(strDirectory)) return 0;
long vReturn = 0;
foreach (string vFile in Directory.GetFiles(strDirectory))
{
FileInfo vFileInfo = new FileInfo(vFile);
vReturn += vFileInfo.Length;
}
foreach (string vDirectory in Directory.GetDirectories(strDirectory))
vReturn += DirectorySize(vDirectory);
return vReturn;
}

------解决方案--------------------
/// <summary>
/// 计算一个目录的大小
/// </summary>
/// <param name= "di "> 指定目录 </param>
/// <param name= "includeSubDir "> 是否包含子目录 </param>
/// <returns> </returns>
private long CalculateDirSize(DirectoryInfo di, bool includeSubDir)
{
long totalSize = 0;

// 检查所有(直接)包含的文件
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
totalSize += file.Length;
}

// 检查所有子目录,如果includeSubDir参数为true
if (includeSubDir)
{
DirectoryInfo[] dirs = di.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
totalSize += CalculateDirSize(dir, includeSubDir);
}
}

return totalSize;
}
------解决方案--------------------
public class NDirectory
{
public static long GetLength(string p_strDirName)
{
#region 参数check
if (!Directory.Exists(p_strDirName)) return 0;
#endregion

#region 変量
string[] files = null;
string[] folders = null;
long length = 0;
#endregion

//文件計算
files = Directory.GetFiles(p_strDirName);
if (files != null)
{
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
length += fileInfo.Length;
}
}

//文件夹計算
folders = Directory.GetDirectories(p_strDirName);
if (folders != null)
{
foreach (string folder in folders)
{
length += NDirectory.GetLength(folder);
}
}

return length;
}

}