• 追加された行はこの色です。
  • 削除された行はこの色です。
#setlinebreak(on);
[[WP TIPS に戻る>wp7/tips]]

*分離ストレージのファイルサイズを取得する [#we5251b4]
サンプルプロジェクト [[RootFrameBackGround.zip>https://skydrive.live.com/redir.aspx?cid=793b87c06d2f0cd5&resid=793B87C06D2F0CD5!1914&parid=793B87C06D2F0CD5!223]]

WP7 でのローカルファイルは分離ストレージ(IsolatedStorage) に格納されており、System.IO.IsolatedStorage 名前空間にある各種クラスを用いてファイルにアクセスします。

しかしながら分離ストレージ関連のクラスにはファイルの作成時間を取得するメソッドなどは存在していますが、ファイルサイズを取得するメソッドは含まれていません。またファイルやフォルダの状態を取得する FileInfo, DirectoryInfo クラスは使用することが出来ない(インスタンス化すると null が返る)ので、標準ではファイルサイズを取得するメソッドは存在していないようです。

ファイルサイズを取得するときは、IsolatedStorageFile.OpenFile メソッドでストリームを開き、そのストリームサイズを取得する必要があります。
 
 using System;
 using System.IO.IsolatedStorage;
 using System.IO;
 
 namespace FileHelper
 {
     public static class IsolatedStorageExtentions
     {
         public static long GetSize(this IsolatedStorageFile i, string filename)
         {
             try
             {
                 if (!i.FileExists(filename))
                     return 0;
 
                 using (IsolatedStorageFileStream stream = i.OpenFile(filename, FileMode.Open))
                 {
                     long length = stream.Length;
                     i.Dispose();
                     return length;
                 }
             }
             catch
             {
                 return 0;
             }
         }
     }
 }

上記のコードを用意しておくと、一発でファイルサイズを取得することが出来ます。

 using FileHelper;
 
 ~中略~
 
 private void Size_Button_Click(object sender, RoutedEventArgs e)
 {
    long size = IsolatedStorageFile.GetUserStoreForApplication().GetSize(filename);
    MessageBox.Show(size.ToString());
 }