如何使用C#获取文件名,大小?

时间:2017-06-29 04:54:09

标签: c#

尝试获取给定目录中文件夹的大小,为我编写的代码。它在目录中抛出错误。帮助找到问题。这是我的代码

        DataTable dt = new DataTable("File Size");
        dt.Columns.Add("Name");
        dt.Columns.Add("Size");

        string[] folderPaths = Directory.GetDirectories(@"C:\Save\");
        long b = 0;
       foreach (string s in folderPaths)
        {
            string[] a = Directory.GetFiles(s, "*.*");
            foreach (string name in a)
             {
                FileInfo info = new FileInfo(name);
                b += info.Length;
              } 
             var row = dt.NewRow();  
             row["Name"] = s.Remove(0, s.LastIndexOf('\\') + 1);
             row["Size"] = b.ToString();
            dt.Rows.Add(row);
        }
     // here dt contain the data in table format with column Name,Size

1 个答案:

答案 0 :(得分:0)

您确定目录存在吗? 此外,您的代码中还有一个错误,因为b永远不会重置,因此每个文件夹都有其大小+之前的大小。

我个人会用:

    public long GetDirSize(DirectoryInfo dir, bool includeSubfolders)
    {
        if (!dir.Exists) return 0;
        return dir.GetFiles("*.*", includeSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Sum(x => x.Length);
    }

完整代码:

DataTable dt = new DataTable("File Size");
dt.Columns.Add("Name");
dt.Columns.Add("Size");// could be dt.Columns.Add("Size", typeof(long))
DirectoryInfo save = new DirectoryInfo(@"C:\Save\");
if (save.Exists)
{
    foreach (var dir in save.GetDirectories())
    {
        var row = dt.NewRow();
        row["Name"] = dir.FullName.TrimEnd('\\');
        // If you want to count also files in subfolders cahnge false to true 
        // If you add column with long type, calling ToString() will not be necessary
        row["Size"] = GetDirSize(dir, false);
        dt.Rows.Add(row);
    }    
}