19

I want to write a file where an external application can read it, but I want also some of the IsolatedStorage advantages, basically insurance against unexpected exceptions. Can I have it?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

3 Answers3

27

You can retrieve the path of an isolated storage file on disk by accessing a private field of the IsolatedStorageFileStream class, by using reflection. Here's an example:


// Create a file in isolated storage.
IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("test.txt", FileMode.Create, store);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("Hello");
writer.Close();
stream.Close();

// Retrieve the actual path of the file using reflection.
string path = stream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream).ToString();

I'm not sure that's a recommended practice though.

Keep in mind that the location on disk depends on the version of the operation system and that you will need to make sure your other application has the permissions to access that location.

mlessard
  • 513
  • 6
  • 13
  • 2
    At least in Silverlight 4, any attempt to do this reflection results in ...A first chance exception of type 'System.FieldAccessException' occurred in mscorlib.dll Additional information: Attempt by method 'Comms.MainPage.LayoutRoot_Loaded(System.Object, System.Windows.RoutedEventArgs)' to access field 'System.IO.IsolatedStorage.IsolatedStorageFile.m_StorePath' failed. Also, it is now "m_StorePath" and not "m_FullPath" - even more reason not to use it. – DJA Jul 21 '11 at 13:02
  • 1
    @DJA That's because you cannot get private members with reflection in Silveright due to security concerns. – ghord Jul 28 '14 at 07:22
10

Instead of creating a temp file and get the location you can get the path from the store directly:

var path = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(store).ToString();
Mohamed Abed
  • 5,025
  • 22
  • 31
9

I use Name property of FileStream.

private static string GetAbsolutePath(string filename)
{
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

    string absoulutePath = null;

    if (isoStore.FileExists(filename))
    {
        IsolatedStorageFileStream output = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore);
        absoulutePath = output.Name;

        output.Close();
        output = null;
    }

    return absoulutePath;
}

This code is tested in Windows Phone 8 SDK.

Tayyab Akram
  • 366
  • 3
  • 12