你如何获得IsolatedStorage中所有文件的平面列表?

时间:2010-06-14 16:06:27

标签: c# .net isolatedstorage isolatedstoragefile

我需要获取给定IsolatedStorage文件夹中所有文件的列表。在IsolatedStorage的根目录下有子文件夹,这些子文件夹需要包含在列表中。

通常的System.IO类不能与IsolatedStorage一起使用。

2 个答案:

答案 0 :(得分:5)

这是我提出的 - 它有效,但我有兴趣看看是否有更好的选择:

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

public static class IsolatedStorageFileExtensions
{

    /// <summary>
    /// Recursively gets a list of all files in isolated storage
    /// </summary>
    /// <remarks>Based on <see cref="http://dotnetperls.com/recursively-find-files"/></remarks>
    /// <param name="isolatedStorageFile"></param>
    /// <returns></returns>
    public static List<string> GetAllFilePaths(this IsolatedStorageFile isolatedStorageFile)
    {
        // Store results in the file results list
        List<string> result = new List<string>();

        // Store a stack of our directories
        Stack<string> stack = new Stack<string>();

        // Add initial directory
        string initialDirectory = "*";
        stack.Push(initialDirectory);

        // Continue while there are directories to process
        while (stack.Count > 0)
        {
            // Get top directory
            string dir = stack.Pop();

            string directoryPath;
            if (dir == "*")
            {
                directoryPath = "*";
            }
            else
            {
                directoryPath = dir + @"\*";
            }

            // Add all files at this directory to the result List
            var filesInCurrentDirectory = isolatedStorageFile.GetFileNames(directoryPath).ToList<string>();

            List<string> filesInCurrentDirectoryWithFolderName = new List<string>();

            // Prefix the filename with the directory name
            foreach (string file in filesInCurrentDirectory)
            {
                filesInCurrentDirectoryWithFolderName.Add(Path.Combine(dir, file));
            }

            result.AddRange(filesInCurrentDirectoryWithFolderName);

            // Add all directories at this directory
            foreach (string directoryName in isolatedStorageFile.GetDirectoryNames(directoryPath))
            {
                stack.Push(directoryName);
            }

        }

        return result;

    }

}

答案 1 :(得分:1)

你是天才,但在检索新目录时,你必须将他们的路径与初始目录结合起来。

// Add all directories at this directory
foreach (string directoryName in isolatedStorageFile.GetDirectoryNames(directoryPath))
{
    stack.Push(Path.Combine(dir,directoryName));
}