我可以获取IsolatedStorage文件的路径并从外部应用程序读取它吗?

Jad*_*ias 17 .net c# isolatedstorage

我想写一个外部应用程序可以读取它的文件,但我也想要一些IsolatedStorage优点,基本上可以防止意外异常.我能拥有吗?

mle*_*ard 26

您可以IsolatedStorageFileStream通过使用反射访问类的私有字段来检索磁盘上的独立存储文件的路径.这是一个例子:


// 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();

Run Code Online (Sandbox Code Playgroud)

我不确定这是推荐的做法.

请记住,磁盘上的位置取决于操作系统的版本,您需要确保其他应用程序具有访问该位置的权限.

  • 至少在Silverlight 4中,任何尝试进行此反射的结果都会导致... mscorlib.dll中出现'System.FieldAccessException'类型的第一次机会异常.附加信息:尝试方法'Comms.MainPage.LayoutRoot_Loaded(System.Object, System.Windows.RoutedEventArgs)'访问字段'System.IO.IsolatedStorage.IsolatedStorageFile.m_StorePath'失败.此外,它现在是"m_StorePath"而不是"m_FullPath" - 更有理由不使用它. (2认同)

Tay*_*ram 9

我使用FileStream的Name属性.

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;
}
Run Code Online (Sandbox Code Playgroud)

此代码在Windows Phone 8 SDK中进行了测试.

  • 在“桌面”.Net 4.5 中,名称为“未知” (3认同)

Moh*_*bed 8

您可以直接从商店获取路径,而不是创建临时文件并获取位置:

var path = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(store).ToString();
Run Code Online (Sandbox Code Playgroud)