Search code examples
c#silverlightwindows-phone-7isolatedstorage

Exception when trying to delete a directory in Isolated Storage


I get the following exception when I try to delete a directory in Isolated Storage in Windows Phone 7:

An error occurred while accessing IsolatedStorage.
there is no inner exception.

using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    isf.DeleteDirectory(dir.TrimEnd('/'));
}

Notes:

  1. putting it in a try-catch will hide the exception but still directory is not deleted!
  2. before calling this I delete all files inside that using DeleteFile() so the problem can not be related to existing files inside the directory.
  3. trimming the directory name is to make sure it's a valid directory name.

Any idea?

Thanks.


Solution

  • Ok, problem solved, problem was that files were not being deleted correctly. The reason I was confused is that IsolatedStorageFile class does not warn you when you are deleting an invalid file. here is the correct code and some notes:

    public static void DeleteDirectoryRecursive(this IsolatedStorageFile isf, string dir)
    {
        foreach (var file in isf.GetFileNames(dir))
        {
            isf.DeleteFile(dir + file);
        }
    
        foreach (var subdir in isf.GetDirectoryNames(dir))
        {
            isf.DeleteDirectoryRecursive(dir + subdir + "\\");
        }
    
        isf.DeleteDirectory(dir.TrimEnd('\\'));
    }
    

    Notes:

    1. there is no difference between '\' and '/' in file paths
    2. trimEnd() is required when DeleteDirectory otherwise exception "path must be a valid file name" is thrown.
    3. GetFileNames() and GetDirectoryNames() return only the name part not the full path. so in order to use each result you need to combine it with the directory (DeleteFile() in this example)