如何:预见独立存储中的空间不足条件

使用独立存储的代码受配额约束,该 配额 指定独立存储文件和目录所在的数据隔离区的最大大小。 配额由安全策略定义,由管理员配置。 如果在尝试写入数据时超出允许的最大大小,IsolatedStorageException则会引发异常,操作将失败。 这有助于防止恶意拒绝服务攻击,这些攻击可能导致应用程序因填充数据存储而拒绝请求。

为了帮助你确定给定的写入尝试是否可能由于此原因而失败,该 IsolatedStorage 类提供三个只读属性: AvailableFreeSpaceUsedSize以及 Quota。 可以使用这些属性来确定写入存储区是否会导致超出存储区的最大允许大小。 请记住,独立存储可以同时被访问,因此,当您计算剩余存储量后尝试写入存储时,存储空间可能已经被占用。 但是,可以使用存储的最大大小来帮助确定是否即将达到可用存储的上限。

Quota 属性取决于程序集的证据才能正常工作。 因此,您应该只对使用IsolatedStorageFileGetUserStoreForAssemblyGetUserStoreForDomain方法创建的对象检索GetStore属性。 IsolatedStorageFile 以任何其他方式创建的对象(例如,从 GetEnumerator 方法返回的对象)不会返回准确的最大大小。

示例:

下面的代码示例获取独立存储、创建几个文件并检索 AvailableFreeSpace 属性。 剩余空间以字节为单位报告。

using System;
using System.IO;
using System.IO.IsolatedStorage;

public class CheckingSpace
{
    public static void Main()
    {
        // Get an isolated store for this assembly and put it into an
        // IsolatedStoreFile object.
        IsolatedStorageFile isoStore =  IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
            IsolatedStorageScope.Assembly, null, null);

        // Create a few placeholder files in the isolated store.
        new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
        new IsolatedStorageFileStream("Another.txt", FileMode.Create, isoStore);
        new IsolatedStorageFileStream("AThird.txt", FileMode.Create, isoStore);
        new IsolatedStorageFileStream("AFourth.txt", FileMode.Create, isoStore);
        new IsolatedStorageFileStream("AFifth.txt", FileMode.Create, isoStore);

        Console.WriteLine(isoStore.AvailableFreeSpace + " bytes of space remain in this isolated store.");
    } // End of Main.
}
Imports System.IO
Imports System.IO.IsolatedStorage

Public Class CheckingSpace
    Public Shared Sub Main()
        ' Get an isolated store for this assembly and put it into an
        ' IsolatedStoreFile object.
        Dim isoStore As IsolatedStorageFile = _
            IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or _
            IsolatedStorageScope.Assembly, Nothing, Nothing)

        ' Create a few placeholder files in the isolated store.
        Dim aStream As New IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore)
        Dim bStream As New IsolatedStorageFileStream("Another.txt", FileMode.Create, isoStore)
        Dim cStream As New IsolatedStorageFileStream("AThird.txt", FileMode.Create, isoStore)
        Dim dStream As New IsolatedStorageFileStream("AFourth.txt", FileMode.Create, isoStore)
        Dim eStream As New IsolatedStorageFileStream("AFifth.txt", FileMode.Create, isoStore)

        Console.WriteLine(isoStore.AvailableFreeSpace + " bytes of space remain in this isolated store.")
    End Sub
End Class

另请参阅