Search code examples
c#windows-phone-7windows-phone-8isolatedstoragedirectory

Easy Way to Recursively Delete Directories in IsolatedStorage on WP7 & 8


In IsolatedStorage you have to delete all the folders and files inside a directory before you can delete the directory itself in IsolatedStorage.

Normally If I'm deleting a directory in IsolatedStorage which has some files inside I would get the list of directories, then use a foreach statement and check if each of those has files then use another foreach statement to delete each of the files inside those directories.

However I have a much more complicated FileSystem going on in IsolatedStorage which looks a bit like this:

Several Main directories which contain Several sub-directories these sub-directories contain another 1-100 additional sub-directories which contain about 3-5 files

At the moment the only technique I know of (using foreach statements and many IsolatedStorageFile.GetUserStoreForApplication().GetDirectoryNames()) is hardly what you would call efficient.

Is there an easier/easy way of checking for recursively deleting directories and their files?


Solution

  • Since the API does not support recursive deletions, so you wlll have to do it yourself. Like e.g.

    public static void DeleteDirectoryRecursively(this IsolatedStorageFile storageFile, String dirName)
    {
        String pattern = dirName + @"\*";
        String[] files = storageFile.GetFileNames(pattern);
        foreach (var fName in files)
        {
            storageFile.DeleteFile(Path.Combine(dirName, fName));
        }
        String[] dirs = storageFile.GetDirectoryNames(pattern);
        foreach (var dName in dirs)
        {
            DeleteDirectoryRecursively(storageFile, Path.Combine(dirName, dName));
        }
        storageFile.DeleteDirectory(dirName);
    }