Udostępnij za pośrednictwem


IsolatedStorageFile Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents an isolated storage area containing files and directories.

Inheritance Hierarchy

System.Object
  System.IO.IsolatedStorage.IsolatedStorageFile

Namespace:  System.IO.IsolatedStorage
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public NotInheritable Class IsolatedStorageFile _
    Implements IDisposable
public sealed class IsolatedStorageFile : IDisposable

The IsolatedStorageFile type exposes the following members.

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 AvailableFreeSpace Gets a value that represents the amount of free space available for isolated storage.
Public propertyStatic member IsEnabled Gets a value that indicates whether isolated storage is enabled.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Quota Gets a value that represents the maximum amount of space available for isolated storage.
Public property UsedSize Gets a value that represents the amount of the space used for isolated storage.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows Phone CopyFile(String, String) Copies an existing file to a new file.
Public methodSupported by Silverlight for Windows Phone CopyFile(String, String, Boolean) Copies an existing file to a new file, and optionally overwrites an existing file.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDirectory Creates a directory in the isolated storage scope.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateFile Creates a file in the isolated store.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 DeleteDirectory Deletes a directory in the isolated storage scope.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 DeleteFile Deletes a file in the isolated store.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 DirectoryExists Determines whether the specified path refers to an existing directory in the isolated store.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Dispose Releases all resources used by the IsolatedStorageFile.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 FileExists Determines whether the specified path refers to an existing file in the isolated store.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetCreationTime Returns the creation date and time of a specified file or directory.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetDirectoryNames() Enumerates the directories in the root of an isolated store.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetDirectoryNames(String) Enumerates directories in an isolated storage scope that match a given pattern.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetFileNames() Obtains the names of files in the root of an isolated store.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetFileNames(String) Enumerates files in isolated storage scope that match a given pattern.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetLastAccessTime Returns the date and time a specified file or directory was last accessed.
Public methodSupported by Silverlight for Windows Phone GetLastWriteTime Returns the date and time a specified file or directory was last written to.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetUserStoreForApplication Obtains user-scoped isolated storage for use by an application that calls from the virtual host domain.
Public methodStatic member GetUserStoreForSite Obtains a user-scoped isolated store for use by all applications in a virtual host domain.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 IncreaseQuotaTo Enables an application to explicitly request a larger quota size, in bytes.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone MoveDirectory Moves a specified directory and its contents to a new location.
Public methodSupported by Silverlight for Windows Phone MoveFile Moves a specified file to a new location, and optionally lets you specify a new file name.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OpenFile(String, FileMode) Opens a file in the specified mode.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OpenFile(String, FileMode, FileAccess) Opens a file in the specified mode with the specified file access.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OpenFile(String, FileMode, FileAccess, FileShare) Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Remove Removes the isolated storage scope and all its contents.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

This class abstracts the virtual file system for isolated storage. An IsolatedStorageFile object corresponds to a specific isolated storage scope, where files represented by IsolatedStorageFileStream objects exist. Applications can use isolated storage to save data in their own isolated portion of the file system, without having to specify a particular path within the file system.

The root of the virtual file system is located in a per-user, obfuscated folder on the physical file system. Each unique identifier provided by the host maps to a different root, which gives each application its own virtual file system. An application cannot navigate out of its own file system into another.

Since isolated stores are scoped to particular assemblies, most other managed code will not be able to access your code's data (highly trusted managed code and administration tools can access stores from other assemblies). Unmanaged code can access any isolated stores.

Examples

The following example shows how to use an IsolatedStorageFile object for most I/O tasks.

Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Input
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Collections
Imports System.Text


Class Example

    Public Shared Sub Demo(ByVal outputBlock As TextBlock)
        ' Obtain an isolated store for an application.
        Try
            Using store As IsolatedStorageFile = _
                IsolatedStorageFile.GetUserStoreForApplication()
                ' Use a StringBuilder to construct output.
                Dim sb As StringBuilder = New StringBuilder

                ' Create three directories in the root.
                store.CreateDirectory("MyApp1")
                store.CreateDirectory("MyApp2")
                store.CreateDirectory("MyApp3")

                ' Create three subdirectories under MyApp1.
                Dim subdirectory1 As String = Path.Combine("MyApp1", "SubDir1")
                Dim subdirectory2 As String = Path.Combine("MyApp1", "SubDir2")
                Dim subdirectory3 As String = Path.Combine("MyApp1", "SubDir3")
                store.CreateDirectory(subdirectory1)
                store.CreateDirectory(subdirectory2)
                store.CreateDirectory(subdirectory3)

                ' Create a file in the root.
                Dim rootFile As IsolatedStorageFileStream = _
                    store.CreateFile("InTheRoot.txt")
                rootFile.Close()


                ' Create a file in a subdirectory.
                Dim subDirFile As IsolatedStorageFileStream = _
                    store.CreateFile(Path.Combine(subdirectory1, "MyApp1A.txt"))
                subDirFile.Close()

                ' Gather file information.
                Dim directoriesInTheRoot() As String = store.GetDirectoryNames

                Dim filesInTheRoot() As String = store.GetFileNames

                Dim searchpath As String = Path.Combine(subdirectory1, "*.*")
                Dim filesInSubDirs() As String = store.GetFileNames(searchpath)

                ' Find subdirectories within the MyApp1
                ' directory using the multi character '*' wildcard.
                Dim subDirectories() As String = _
                    store.GetDirectoryNames(Path.Combine("MyApp1", "*"))

                ' List file infomration

                ' List the directories in the root.
                sb.AppendLine("Directories in root:")
                For Each dir As String In directoriesInTheRoot
                    sb.AppendLine((" - " + dir))
                Next
                sb.AppendLine()
                ' List the subdirectories under MyApp1.
                sb.AppendLine("Directories under MyApp1:")
                For Each sDir As String In subDirectories
                    sb.AppendLine((" - " + sDir))
                Next
                sb.AppendLine()
                ' List files in the root.
                sb.AppendLine("Files in the root:")
                For Each fileName As String In filesInTheRoot
                    sb.AppendLine((" - " + fileName))
                Next
                sb.AppendLine()
                ' List files in MyApp1\SubDir1.
                sb.AppendLine("Files in MyApp1\SubDir1:")
                For Each fileName As String In filesInSubDirs
                    sb.AppendLine((" - " + fileName))
                Next
                sb.AppendLine()

                ' Write to an existing file: MyApp1\SubDir1\MyApp1A.txt

                ' Determine if the file exists before writing to it.
                Dim filePath As String = Path.Combine(subdirectory1, "MyApp1A.txt")

                If store.FileExists(filePath) Then
                    Try
                        Using sw As StreamWriter = _
                            New StreamWriter(store.OpenFile(filePath, FileMode.Open, FileAccess.Write))

                            sw.WriteLine("To do list:")
                            sw.WriteLine("1. Buy supplies.")
                        End Using

                    Catch ex As IsolatedStorageException
                        sb.AppendLine(ex.Message)
                    End Try
                Else
                    sb.AppendLine((filePath + "does not exist"))
                End If

                ' Read the contents of the file: MyApp1\SubDir1\MyApp1A.txt
                Try
                    Using reader As StreamReader = _
                        New StreamReader(store.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                        Dim contents As String = reader.ReadToEnd
                        sb.AppendLine(filePath + " contents:")
                        sb.AppendLine(contents)
                    End Using
                Catch ex As IsolatedStorageException
                    sb.Append(ex.Message)
                End Try


                ' Delete a file.
                Try
                    If store.FileExists(filePath) Then
                        store.DeleteFile(filePath)
                    End If
                Catch ex As IsolatedStorageException
                    sb.AppendLine(ex.Message)
                End Try

                ' Delete a specific directory.
                Dim dirDelete As String = Path.Combine("MyApp1", "SubDir3")
                Try
                    If store.DirectoryExists(dirDelete) Then
                        store.DeleteDirectory(dirDelete)
                    End If
                Catch ex As IsolatedStorageException
                    sb.AppendLine(ex.Message)
                End Try

                sb.AppendLine()
                ' remove the store
                store.Remove()

                sb.AppendLine("Store removed.")
                outputBlock.Text = sb.ToString()
            End Using
        Catch Ex As IsolatedStorageException
            ' TODO: Handle that store was unable to be accessed.
        End Try
    End Sub
End Class

' Quota status in increase examples
Class StoreQuota

    ' Assumes an event handler for the MouseLeftbuttonUp
    ' event is defined for a control named 'IncreaseQuota'
    ' In the control's XAML: MouseLeftButtonUp="IncreaseQuota_OnLeftMouseButtonUp"
    Public Sub IncreaseQuota_OnClick(ByVal sender As Object, ByVal e As MouseEventArgs)
        ' Obtain an isolated store for an application.
        Try
            Using store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
                ' Request 5MB more space in bytes.
                Dim spaceToAdd As Int64 = 5242880
                Dim curAvail As Int64 = store.AvailableFreeSpace
                ' If available space is less than
                ' what is requested, try to increase.
                If (curAvail < spaceToAdd) Then
                    ' Request more quota space.
                    If Not store.IncreaseQuotaTo((store.Quota + spaceToAdd)) Then
                        ' The user clicked NO to the
                        ' host's prompt to approve the quota increase.
                    Else
                        ' The user clicked YES to the
                        ' host's prompt to approve the quota increase.
                    End If
                End If
            End Using
        Catch Ex As IsolatedStorageException

            ' TODO: Handle that store could not be accessed.
        End Try
    End Sub




    Public Shared Sub ShowIsoStoreStatus(ByVal inputBlock As TextBlock)
        ' Obtain an isolated store for an application.
        Try
            Using store As IsolatedStorageFile = _
              IsolatedStorageFile.GetUserStoreForApplication()
                Dim spaceUsed As String = (store.Quota - store.AvailableFreeSpace).ToString
                Dim spaceAvailable As String = store.AvailableFreeSpace.ToString
                Dim curQuota As String = store.Quota.ToString
                inputBlock.Text = String.Format("Quota: {0} bytes, Used: {1} bytes, Available: {2} bytes", _
                                         curQuota, spaceUsed, spaceAvailable)
            End Using
        Catch Ex As IsolatedStorageException
            inputBlock.Text = "Unable to access store."
        End Try
    End Sub
End Class

' This example's Example.Demo method 
' produces the following output:
' -----
' Directories in root:
' - MyApp1
' - MyApp2
' - MyApp3

' Directories under MyApp1:
' - SubDir1
' - SubDir2
' - SubDir3

' Files in the root:
' - InTheRoot.txt

' Files in MyApp1\SubDir1:
' - MyApp1A.txt

' MyApp1\SubDir1\MyApp1A.txt contents:
' To do list:
' 1. Buy supplies.

' Store removed.
' -----

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections;
using System.Text;

class Example
{
    public static void Demo(TextBlock outputBlock)
    {
        // Obtain an isolated store for an application.
        try
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Use a StringBuilder to construct output.
                StringBuilder sb = new StringBuilder();

                // Create three directories in the root.
                store.CreateDirectory("MyApp1");
                store.CreateDirectory("MyApp2");
                store.CreateDirectory("MyApp3");

                // Create three subdirectories under MyApp1.
                string subdirectory1 = Path.Combine("MyApp1", "SubDir1");
                string subdirectory2 = Path.Combine("MyApp1", "SubDir2");
                string subdirectory3 = Path.Combine("MyApp1", "SubDir3");
                store.CreateDirectory(subdirectory1);
                store.CreateDirectory(subdirectory2);
                store.CreateDirectory(subdirectory3);

                // Create a file in the root.
                IsolatedStorageFileStream rootFile = store.CreateFile("InTheRoot.txt");
                rootFile.Close();

                // Create a file in a subdirectory.
                IsolatedStorageFileStream subDirFile =
                    store.CreateFile(Path.Combine(subdirectory1, "MyApp1A.txt"));
                subDirFile.Close();

                // Gather file information
                string[] directoriesInTheRoot = store.GetDirectoryNames();

                string[] filesInTheRoot = store.GetFileNames();

                string searchpath = Path.Combine(subdirectory1, "*.*");
                string[] filesInSubDirs = store.GetFileNames(searchpath);

                // Find subdirectories within the MyApp1
                // directory using the multi character '*' wildcard.
                string[] subDirectories =
                    store.GetDirectoryNames(Path.Combine("MyApp1", "*"));

                // List file information

                // List the directories in the root.
                sb.AppendLine("Directories in root:");
                foreach (string dir in directoriesInTheRoot)
                {
                    sb.AppendLine(" - " + dir);
                }
                sb.AppendLine();

                // List the subdirectories under MyApp1.
                sb.AppendLine("Directories under MyApp1:");
                foreach (string sDir in subDirectories)
                {
                    sb.AppendLine(" - " + sDir);
                }
                sb.AppendLine();

                // List files in the root.
                sb.AppendLine("Files in the root:");
                foreach (string fileName in filesInTheRoot)
                {
                    sb.AppendLine(" - " + fileName);
                }
                sb.AppendLine();

                // List files in MyApp1\SubDir1.
                sb.AppendLine(@"Files in MyApp1\SubDir1:");
                foreach (string fileName in filesInSubDirs)
                {
                    sb.AppendLine(" - " + fileName);
                }
                sb.AppendLine();

                // Write to an existing file: MyApp1\SubDir1\MyApp1A.txt

                // Determine if the file exists before writing to it.
                string filePath = Path.Combine(subdirectory1, "MyApp1A.txt");

                if (store.FileExists(filePath))
                {
                    try
                    {
                        using (StreamWriter sw =
                            new StreamWriter(store.OpenFile(filePath,
                                FileMode.Open, FileAccess.Write)))
                        {
                            sw.WriteLine("To do list:");
                            sw.WriteLine("1. Buy supplies.");
                        }
                    }
                    catch (IsolatedStorageException ex)
                    {

                        sb.AppendLine(ex.Message);
                    }
                }

                // Read the contents of the file: MyApp1\SubDir1\MyApp1A.txt
                try
                {
                    using (StreamReader reader =
                        new StreamReader(store.OpenFile(filePath,
                            FileMode.Open, FileAccess.Read)))
                    {
                        string contents = reader.ReadToEnd();
                        sb.AppendLine(filePath + " contents:");
                        sb.AppendLine(contents);
                    }
                }
                catch (IsolatedStorageException ex)
                {

                    sb.AppendLine(ex.Message);
                }

                // Delete a file.
                try
                {
                    if (store.FileExists(filePath))
                    {
                        store.DeleteFile(filePath);
                    }
                }
                catch (IsolatedStorageException ex)
                {
                    sb.AppendLine(ex.Message);
                }

                // Delete a specific directory.
                string dirDelete = Path.Combine("MyApp1", "SubDir3");
                try
                {
                    if (store.DirectoryExists(dirDelete))
                    {
                        store.DeleteDirectory(dirDelete);
                    }
                }
                catch (IsolatedStorageException ex)
                {
                    sb.AppendLine(ex.Message);
                }


                sb.AppendLine();


                // remove the store
                store.Remove();

                sb.AppendLine("Store removed.");

                outputBlock.Text = sb.ToString();
            }
        }
        catch (IsolatedStorageException)
        {
            // TODO: Handle that store was unable to be accessed.

        }
    }
}

// Quota status and increase quota examples
class StoreQuota
{

    // Assumes an event handler for the MouseLeftbuttonUp
    // event is defined for a control named 'IncreaseQuota'
    // In the control's XAML: MouseLeftButtonUp="IncreaseQuota_OnLeftMouseButtonUp"

    // User first selects UI to increase the quota.
    public void IncreaseQuota_OnClick(object sender, MouseEventArgs e)
    {

        // Obtain an isolated store for an application.
        try
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Request 5MB more space in bytes.
                Int64 spaceToAdd = 5242880;
                Int64 curAvail = store.AvailableFreeSpace;

                // If available space is less than
                // what is requested, try to increase.
                if (curAvail < spaceToAdd)
                {

                    // Request more quota space.
                    if (!store.IncreaseQuotaTo(store.Quota + spaceToAdd))
                    {
                        // The user clicked NO to the
                        // host's prompt to approve the quota increase.
                    }
                    else
                    {
                        // The user clicked YES to the
                        // host's prompt to approve the quota increase.
                    }
                }
            }
        }

        catch (IsolatedStorageException)
        {
            // TODO: Handle that store could not be accessed.

        }
    }

    public static void ShowIsoStoreStatus(TextBlock inputBlock)
    {

        // Obtain an isolated store for an application.
        try
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string spaceUsed = (store.Quota - store.AvailableFreeSpace).ToString();
                string spaceAvailable = store.AvailableFreeSpace.ToString();
                string curQuota = store.Quota.ToString();
                inputBlock.Text =
                    String.Format("Quota: {0} bytes, Used: {1} bytes, Available: {2} bytes",
                            curQuota, spaceUsed, spaceAvailable);
            }
        }

        catch (IsolatedStorageException)
        {
            inputBlock.Text = "Unable to access store.";

        }
    }

}
// This example's Example.Demo method
// produces the following output:
// -----
// Directories in root:
// - MyApp1
// - MyApp2
// - MyApp3

// Directories under MyApp1:
// - SubDir1
// - SubDir2
// - SubDir3

// Files in the root:
// - InTheRoot.txt

// Files in MyApp1\SubDir1:
// - MyApp1A.txt

// MyApp1\SubDir1\MyApp1A.txt contents:
// To do list:
// 1. Buy supplies.

// Store removed.
// -----

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.