Metro Nuggets

Bitesized tidbits for building Modern (Metro) apps.

Deleting All Content From an IsolatedStorage Folder

Deleting a folder from IsolatedStorage is easy, you know, assuming it’s empty. But what if it’s not? What if you just want to delete a folder regardless of what, or how much, stuff is in there? Well you have to go through and delete not only the files in the folder, but also any subfolders and the files within them. That’s a lot more code than you would think is required for this operation.

The Solution

To overcome this, I’ve written a quick little extension method

        /// <summary>
        /// Deletes the folder.
        /// </summary>
        /// The isolated storage folder.
        /// The path to delete.
        public static void DeleteFolder(this IsolatedStorageFile iso, string path)
        {
            if (!iso.DirectoryExists(path))
                return;
            // Get the subfolders that reside under path
            var folders = iso.GetDirectoryNames(Path.Combine(path, "*.*"));

            // Iterate through the subfolders and check for further subfolders            
            foreach (var folder in folders)
            {
                string folderName = path + "/" + folder;
                iso.DeleteFolder(folderName);                
            }
            // Delete all files at the root level in that folder.
            foreach (var file in iso.GetFileNames(Path.Combine(path, "*.*")))
            {
                iso.DeleteFile(Path.Combine(path, file));
            }
            // Finally delete the path
            iso.DeleteDirectory(path);
        }

Usage

Its usage is simple as you can see from the extension method itself:

IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
iso.DeleteFolder("cache");

And that’s it.

SL

Advertisements

2 responses to “Deleting All Content From an IsolatedStorage Folder

  1. pratyay July 19, 2014 at 13:24

    is “cache” the default folder for the isolated storage.??i usually save my contents just with the file name…(not in a specific folder)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: