2013年3月13日水曜日

あるフォルダ以下の全ファイルサイズの合計を求める処理をLINQで。

サンプルとして、あるフォルダ以下のすべてのファイルの、合計サイズを算出するアプリケーションを作ります。

VS2012 Express for Desktopを使って、コンソールアプリケーションを作り、第一引数に総サイズを取得したいフォルダを指定するものとします。

フォルダ以下のフォルダの列挙、ファイルの列挙はSystem.IO.Directoryクラスを、ファイルのサイズを取得するにはSystem.IO.FileInfoクラスを使います。そして、フォルダ以下のすべてのファイルを取得するには再帰を使う必要があるでしょう。

出来上がったコードはこちら。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace GetTotal
{
  class Program
  {
    static void Main(string[] args)
    {
      if(args.Length < 1)
      {
        Console.Error.WriteLine("Less argument.");
        return;
      }

      try
      {
        Func<string, long> gettotal = null;
        gettotal = p =>
            Directory.GetDirectories(p).Select(f => gettotal(f)).Sum() +
            Directory.GetFiles(p).Select(f => new FileInfo(f).Length).Sum();
        Console.WriteLine("Size: {0:#,0} Bytes", gettotal(args[0]));
      }
      catch(Exception e)
      {
          Console.Error.WriteLine(e.Message);
      }
    }
  }
}

VS2012のプログラムフォルダで試してみました。


うん。うまくいった。


でも、21~24行目は本当はこう書きたかった。

Func<string, long> gettotal = p => 
    Directory.GetDirectories(p).Select(f => gettotal(f)).Sum() +
    Directory.GetFiles(p).Select(f => new FileInfo(f).Length).Sum();

『未割当のローカル変数 'gettotal' が使用されました。』と怒られるのでした。仕方ない。ぐぅ。

0 件のコメント:

コメントを投稿