如何:获取独立存储的存储区
存储区公开数据隔离舱中的虚拟文件系统。 IsolatedStorageFile 提供了许多与存储区进行交互的方法。 为了创建和检索存储区,IsolatedStorageFile 提供了三种静态方法。 调用 GetUserStoreForAssembly 可返回按用户和程序集隔离的存储区。 调用 GetUserStoreForDomain 可返回按域和程序集隔离的存储区。 这两种方法检索属于代码块(是从该代码块中调用这两种方法的)的存储区。 静态方法 GetStore 返回通过传入范围参数组合指定的独立存储区。 下面的参数返回一个按用户、程序集和域隔离的存储区。
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or
IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, Nothing, Nothing)
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null);
IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User |
IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain, (Type ^)nullptr, (Type ^)nullptr);
GetStore 方法可用于指定存储区应该和漫游用户配置文件一起漫游。 有关如何对此进行设置的详细信息,请参见独立存储和漫游。
默认情况下,从不同的程序集中获得的独立存储区是不同的。 您可以访问不同程序集或域的存储区,方法是传入不同的程序集或域凭据作为 GetStore 方法的最后两个参数。 这需要访问按应用程序域标识隔离的独立存储的权限。 有关更多信息,请参见 GetStore 方法。
三种方法中的每种方法都返回 IsolatedStorageFile 对象。 要帮助您确定哪种隔离类型最适合您的情况,请参见隔离的类型。 一旦具有了独立存储文件对象之后,您便可以使用独立存储方法来读取、写入、创建和删除文件及文件目录了。
没有一种机制可用来防止代码向没有足够访问权限来自己获取存储区的代码传递 IsolatedStorageFile。 只有当获得对 IsolatedStorage 对象的引用时(通常是在 GetUserStoreForAssembly、GetUserStoreForDomain 或 GetStore 方法中),才检查域和程序集标识及独立存储权限。 因此,使用这些引用的代码应该负责保护对 IsolatedStorageFile 对象的引用。
ObtainingAStore 示例
下面的代码示例是一个非常简单的由类获得按用户和程序集隔离的存储区的示例。 通过向 GetStore 方法传递的参数添加 IsolatedStorageScope.Domain,此代码可更改为检索按用户、域和程序集隔离的存储区。
运行代码之后,您可以通过在命令行中键入 StoreAdm /LIST 来确认已创建了存储区。 这将运行独立存储管理工具 (Storeadm.exe) 并列出用户当前所有的独立存储区。 有关 Storeadm.exe 的更多信息,请参见独立存储工具。
Imports System
Imports System.IO.IsolatedStorage
Public Class ObtainingAStore
Public Shared Sub Main()
' Get a new isolated store for this assembly and put it into an
' isolated store object.
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or
IsolatedStorageScope.Assembly, Nothing, Nothing)
End Sub
End Class
using System;
using System.IO.IsolatedStorage;
public class ObtainingAStore
{
public static void Main()
{
// Get a new isolated store for this assembly and put it into an
// isolated store object.
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
IsolatedStorageScope.Assembly, null, null);
}
}
using namespace System;
using namespace System::IO::IsolatedStorage;
public ref class ObtainingAStore
{
public:
static void Main()
{
// Get a new isolated store for this assembly and put it into an
// isolated store object.
IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User |
IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr);
}
};