Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

IsolatedStorageFileStream Class

Exposes a file within isolated storage.

System.Object
  System.MarshalByRefObject
    System.IO.Stream
      System.IO.FileStream
        System.IO.IsolatedStorage.IsolatedStorageFileStream

Namespace:  System.IO.IsolatedStorage
Assembly:  mscorlib (in mscorlib.dll)
[ComVisibleAttribute(true)]
public class IsolatedStorageFileStream : FileStream

The IsolatedStorageFileStream type exposes the following members.

  NameDescription
Public methodIsolatedStorageFileStream(String, FileMode)Initializes a new instance of an IsolatedStorageFileStream object giving access to the file designated by path in the specified mode.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the kind of access requested.
Public methodIsolatedStorageFileStream(String, FileMode, IsolatedStorageFile)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, and in the context of the IsolatedStorageFile specified by isf.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess, FileShare)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess, IsolatedStorageFile)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path in the specified mode, with the specified file access, and in the context of the IsolatedStorageFile specified by isf.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, with the buffersize specified.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, IsolatedStorageFile)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, and in the context of the IsolatedStorageFile specified by isf.
Public methodIsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32, IsolatedStorageFile)Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, with the buffersize specified, and in the context of the IsolatedStorageFile specified by isf.
Top
  NameDescription
Public propertyCanReadGets a Boolean value indicating whether the file can be read. (Overrides FileStream.CanRead.)
Public propertyCanSeekGets a Boolean value indicating whether seek operations are supported. (Overrides FileStream.CanSeek.)
Public propertyCanTimeoutGets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public propertyCanWriteGets a Boolean value indicating whether you can write to the file. (Overrides FileStream.CanWrite.)
Public propertyHandle Obsolete. Gets the file handle for the file that the current IsolatedStorageFileStream object encapsulates. Accessing this property is not permitted on an IsolatedStorageFileStream object, and throws an IsolatedStorageException. (Overrides FileStream.Handle.)
Public propertyIsAsyncGets a Boolean value indicating whether the IsolatedStorageFileStream object was opened asynchronously or synchronously. (Overrides FileStream.IsAsync.)
Public propertyLengthGets the length of the IsolatedStorageFileStream object. (Overrides FileStream.Length.)
Public propertyNameGets the name of the FileStream that was passed to the constructor. (Inherited from FileStream.)
Public propertyPositionGets or sets the current position of the current IsolatedStorageFileStream object. (Overrides FileStream.Position.)
Public propertyReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public propertySafeFileHandleGets a SafeFileHandle object that represents the operating system file handle for the file that the current IsolatedStorageFileStream object encapsulates. (Overrides FileStream.SafeFileHandle.)
Public propertyWriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top
  NameDescription
Public methodBeginReadBegins an asynchronous read. (Overrides FileStream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).)
Public methodBeginWriteBegins an asynchronous write. (Overrides FileStream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).)
Public methodCloseCloses the current stream and releases any resources (such as sockets and file handles) associated with the current stream. (Inherited from Stream.)
Public methodCopyTo(Stream)Reads the bytes from the current stream and writes them to the destination stream. (Inherited from Stream.)
Public methodCopyTo(Stream, Int32)Reads all the bytes from the current stream and writes them to a destination stream, using a specified buffer size. (Inherited from Stream.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected methodCreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public methodDispose()Releases all resources used by the Stream. (Inherited from Stream.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the IsolatedStorageFileStream and optionally releases the managed resources. (Overrides FileStream.Dispose(Boolean).)
Public methodEndReadEnds a pending asynchronous read request. (Overrides FileStream.EndRead(IAsyncResult).)
Public methodEndWriteEnds an asynchronous write. (Overrides FileStream.EndWrite(IAsyncResult).)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeEnsures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream. (Inherited from FileStream.)
Public methodFlush()Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides FileStream.Flush().)
Public methodFlush(Boolean)Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers. (Overrides FileStream.Flush(Boolean).)
Public methodGetAccessControlGets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object. (Inherited from FileStream.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodLockPrevents other processes from reading from or writing to the FileStream. (Inherited from FileStream.)
Protected methodMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodObjectInvariantInfrastructure. Provides support for a Contract. (Inherited from Stream.)
Public methodReadCopies bytes from the current buffered IsolatedStorageFileStream object to an array. (Overrides FileStream.Read(Byte[], Int32, Int32).)
Public methodReadByteReads a single byte from the IsolatedStorageFileStream object in isolated storage. (Overrides FileStream.ReadByte().)
Public methodSeekSets the current position of this IsolatedStorageFileStream object to the specified value. (Overrides FileStream.Seek(Int64, SeekOrigin).)
Public methodSetAccessControlApplies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object. (Inherited from FileStream.)
Public methodSetLengthSets the length of this IsolatedStorageFileStream object to the specified value. (Overrides FileStream.SetLength(Int64).)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodUnlockAllows access by other processes to all or part of a file that was previously locked. (Inherited from FileStream.)
Public methodWriteWrites a block of bytes to the IsolatedStorageFileStream object using data read from a byte array. (Overrides FileStream.Write(Byte[], Int32, Int32).)
Public methodWriteByteWrites a single byte to the IsolatedStorageFileStream object. (Overrides FileStream.WriteByte(Byte).)
Top

Use this class to read, write and create files in isolated storage.

Since this class extends FileStream, you can use an instance of IsolatedStorageFileStream in most situations where a FileStream might otherwise be used, such as to construct a StreamReader or StreamWriter.

The following console application demonstrates how you can use IsolatedStorageFile and IsolatedStorageFileStream to write data to an Isolated Storage file. The user is requested to log in. If the user is a new user, a News URL and a Sports URL are recorded as personal preferences in Isolated Storage. If the user is a returning user, the user's current preferences are displayed. The code examples used throughout this namespace are presented in the context of this sample application. You can use the Storeadm.exe (Isolated Storage Tool) utility to list and remove the Isolated Storage files that are created with this console application.


// This sample demonstrates methods of classes found in the System.IO IsolatedStorage namespace.
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Policy;
using Microsoft.Win32.SafeHandles;
using System.Security.Permissions;

[assembly: CLSCompliantAttribute(true)]

class ConsoleApp
{
    [STAThread]
    static void Main(string[] args)
    {

        // Prompt the user for their username.

        Console.WriteLine("Login:");

        // Does no error checking.
        LoginPrefs lp = new LoginPrefs(Console.ReadLine());

        if (lp.NewPrefs)
        {
            Console.WriteLine("Please set preferences for a new user.");
            GatherInfoFromUser(lp);

            // Write the new preferences to storage.
            double percentUsed = lp.SetPrefsForUser();
            Console.WriteLine("Your preferences have been written. Current space used is " + percentUsed.ToString() + " %");
        }
        else
        {
            Console.WriteLine("Welcome back.");

            Console.WriteLine("Your preferences have expired, please reset them.");
            GatherInfoFromUser(lp);
            lp.SetNewPrefsForUser();

            Console.WriteLine("Your news site has been set to {0}\n and your sports site has been set to {1}.", lp.NewsUrl, lp.SportsUrl);
        }
        lp.GetIsoStoreInfo();
        Console.WriteLine("Enter 'd' to delete the IsolatedStorage files and exit, or press any other key to exit without deleting files.");
        string consoleInput = Console.ReadLine();
        if (consoleInput.ToLower() == "d")
        {
            lp.DeleteFiles();
            lp.DeleteDirectories();
        }

    }

    static void GatherInfoFromUser(LoginPrefs lp)
    {
        Console.WriteLine("Please enter the URL of your news site.");
        lp.NewsUrl = Console.ReadLine();
        Console.WriteLine("Please enter the URL of your sports site.");
        lp.SportsUrl = Console.ReadLine();
    }
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public class LoginPrefs
{
    public LoginPrefs(string myUserName)
    {
        userName = myUserName;
        myNewPrefs = GetPrefsForUser();
    }
    string userName;

    string myNewsUrl;
    public string NewsUrl
    {
        get { return myNewsUrl; }
        set { myNewsUrl = value; }
    }

    string mySportsUrl;
    public string SportsUrl
    {
        get { return mySportsUrl; }
        set { mySportsUrl = value; }
    }
    bool myNewPrefs;
    public bool NewPrefs
    {
        get { return myNewPrefs; }
    }

    private bool GetPrefsForUser()
    {
        try
        {

            // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
            IsolatedStorageFile isoFile =
                IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                null,
                null);

            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read);

            // The code executes to this point only if a file corresponding to the username exists.
            // Though you can perform operations on the stream, you cannot get a handle to the file.

            try
            {

                SafeFileHandle aFileHandle = isoStream.SafeFileHandle;
                Console.WriteLine("A pointer to a file handle has been obtained. "
                    + aFileHandle.ToString() + " "
                    + aFileHandle.GetHashCode());
            }

            catch (Exception e)
            {
                // Handle the exception.
                Console.WriteLine("Expected exception");
                Console.WriteLine(e);
            }

            StreamReader reader = new StreamReader(isoStream);
            // Read the data.
            this.NewsUrl = reader.ReadLine();
            this.SportsUrl = reader.ReadLine();
            reader.Close();
            isoFile.Close();
            return false;
        }
        catch (System.IO.FileNotFoundException)
        {
            // Expected exception if a file cannot be found. This indicates that we have a new user.
            return true;
        }
    }
    public bool GetIsoStoreInfo()
    {
        // Get a User store with type evidence for the current Domain and the Assembly.
        IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
            IsolatedStorageScope.Assembly |
            IsolatedStorageScope.Domain,
            typeof(System.Security.Policy.Url),
            typeof(System.Security.Policy.Url));

        String[] dirNames = isoFile.GetDirectoryNames("*");
        String[] fileNames = isoFile.GetFileNames("*");

        // List directories currently in this Isolated Storage.
        if (dirNames.Length > 0)
        {
            for (int i = 0; i < dirNames.Length; ++i)
            {
                Console.WriteLine("Directory Name: " + dirNames[i]);
            }
        }

        // List the files currently in this Isolated Storage.
        // The list represents all users who have personal preferences stored for this application.
        if (fileNames.Length > 0)
        {
            for (int i = 0; i < fileNames.Length; ++i)
            {
                Console.WriteLine("File Name: " + fileNames[i]);
            }
        }

        isoFile.Close();
        return true;
    }

    public double SetPrefsForUser()
    {
        try
        {
            IsolatedStorageFile isoFile;
            isoFile = IsolatedStorageFile.GetUserStoreForDomain();

            // Open or create a writable file.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                isoFile);

            StreamWriter writer = new StreamWriter(isoStream);
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);
            // Calculate the amount of space used to record the user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Dispose();
            isoFile.Close();
            return d;
        }
        catch (IsolatedStorageException ex)
        {
            // Add code here to handle the exception.
            Console.WriteLine(ex);
            return 0.0;
        }
    }

    public void DeleteFiles()
    {
        try
        {
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));

            String[] dirNames = isoFile.GetDirectoryNames("*");
            String[] fileNames = isoFile.GetFileNames("*");

            // List the files currently in this Isolated Storage.
            // The list represents all users who have personal
            // preferences stored for this application.
            if (fileNames.Length > 0)
            {
                for (int i = 0; i < fileNames.Length; ++i)
                {
                    // Delete the files.
                    isoFile.DeleteFile(fileNames[i]);
                }
                // Confirm that no files remain.
                fileNames = isoFile.GetFileNames("*");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
    // This method deletes directories in the specified Isolated Storage, after first 
    // deleting the files they contain. In this example, the Archive directory is deleted. 
    // There should be no other directories in this Isolated Storage.
    public void DeleteDirectories()
    {
        try
        {
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));
            String[] dirNames = isoFile.GetDirectoryNames("*");
            String[] fileNames = isoFile.GetFileNames("Archive\\*");

            // Delete all the files currently in the Archive directory.

            if (fileNames.Length > 0)
            {
                for (int i = 0; i < fileNames.Length; ++i)
                {
                    // Delete the files.
                    isoFile.DeleteFile("Archive\\" + fileNames[i]);
                }
                // Confirm that no files remain.
                fileNames = isoFile.GetFileNames("Archive\\*");
            }


            if (dirNames.Length > 0)
            {
                for (int i = 0; i < dirNames.Length; ++i)
                {
                    // Delete the Archive directory.
                }
            }
            dirNames = isoFile.GetDirectoryNames("*");
            isoFile.Remove();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    public double SetNewPrefsForUser()
    {
        try
        {
            byte inputChar;
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));

            // If this is not a new user, archive the old preferences and 
            // overwrite them using the new preferences.
            if (!this.myNewPrefs)
            {
                if (isoFile.GetDirectoryNames("Archive").Length == 0)
                    isoFile.CreateDirectory("Archive");
                else
                {

                    IsolatedStorageFileStream source =
                        new IsolatedStorageFileStream(this.userName, FileMode.OpenOrCreate,
                        isoFile);
                    // This is the stream from which data will be read.
                    Console.WriteLine("Is the source file readable? " + (source.CanRead ? "true" : "false"));
                    Console.WriteLine("Creating new IsolatedStorageFileStream for Archive.");

                    // Open or create a writable file.
                    IsolatedStorageFileStream target =
                        new IsolatedStorageFileStream("Archive\\ " + this.userName,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Write,
                        isoFile);
                    Console.WriteLine("Is the target file writable? " + (target.CanWrite ? "true" : "false"));
                    // Stream the old file to a new file in the Archive directory.
                    if (source.IsAsync && target.IsAsync)
                    {
                        // IsolatedStorageFileStreams cannot be asynchronous.  However, you
                        // can use the asynchronous BeginRead and BeginWrite functions
                        // with some possible performance penalty.

                        Console.WriteLine("IsolatedStorageFileStreams cannot be asynchronous.");
                    }

                    else
                    {
                        Console.WriteLine("Writing data to the new file.");
                        while (source.Position < source.Length)
                        {
                            inputChar = (byte)source.ReadByte();
                            target.WriteByte(inputChar);
                        }

                        // Determine the size of the IsolatedStorageFileStream
                        // by checking its Length property.
                        Console.WriteLine("Total Bytes Read: " + source.Length);

                    }

                    // After you have read and written to the streams, close them.
                    target.Close();
                    source.Close();
                }
            }

            // Open or create a writable file with a maximum size of 10K.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                FileShare.Write,
                10240,
                isoFile);
            isoStream.Position = 0;  // Position to overwrite the old data.
            StreamWriter writer = new StreamWriter(isoStream);
            // Update the data based on the new inputs.
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);

            // Calculate the amount of space used to record this user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Close();

            return d;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return 0.0;
        }
    }
}



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.