次の方法で共有


IsolatedStorageFile クラス

ファイルとディレクトリを格納している分離ストレージ領域を表します。

この型のすべてのメンバの一覧については、IsolatedStorageFile メンバ を参照してください。

System.Object
   System.MarshalByRefObject
      System.IO.IsolatedStorage.IsolatedStorage
         System.IO.IsolatedStorage.IsolatedStorageFile

NotInheritable Public Class IsolatedStorageFile
   Inherits IsolatedStorage
   Implements IDisposable
[C#]
public sealed class IsolatedStorageFile : IsolatedStorage,
   IDisposable
[C++]
public __gc __sealed class IsolatedStorageFile : public
   IsolatedStorage, IDisposable
[JScript]
public class IsolatedStorageFile extends IsolatedStorage implements
   IDisposable

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

このオブジェクトは、 IsolatedStorageFileStream オブジェクトによって表されるファイルが存在する特定の分離ストレージ スコープに対応しています。アプリケーションは、分離ストレージを使用することで、ファイル システム内の特定のパスを指定しなくても、ファイル システム内の分離された独自の領域にデータを保存できます。分離ストアのスコープは特定のアセンブリに限定されているため、他の多くのマネージ コードからは、コードのデータにアクセスできません。ただし、信頼性の高いマネージ コードや管理ツールは、他のアセンブリからもストアにアクセスできます。アンマネージ コードの場合は、どの分離ストアにもアクセスできます。

使用例

[Visual Basic, C#, C++] 次のコンソール アプリケーションでは、 IsolatedStorageFileIsolatedStorageFileStream を使用して、分離ストレージ ファイルにデータを書き込む例を示しています。このアプリケーションでは、ユーザーはログインを要求されます。ユーザーが新規ユーザーの場合は、News 用 URL および Sports 用 URL が分離ストレージファイルに個人用の環境設定として記録されます。ユーザーが以前にもログインしたことのある場合は、そのユーザーの現在の環境設定が表示されます。この名前空間全体を通じて使用するコード例は、このサンプル アプリケーションを前提としています。

[Visual Basic, C#, C++] 分離ストレージ ツール (Storeadm.exe) ユーティリティを使用すると、このコンソール アプリケーションで作成された分離ストレージファイルを一覧および削除できます。

 
Imports System
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Security.Policy
Imports Microsoft.VisualBasic



Namespace ISOCS
    _
    Class ConsoleApp


        <STAThread()> Overloads Shared _
       Sub Main(ByVal args() As String)

            ' Prompt the user for their username.
            Console.WriteLine("Enter your login ID:")

            ' Does no error checking.
            Dim lp As New LoginPrefs(Console.ReadLine())

            If lp.NewPrefs Then
                Console.WriteLine("Please set preferences for a new user.")
                GatherInfoFromUser(lp)

                ' Write the new preferences to storage.
                Dim percentUsed As Double = 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}" & ControlChars.Cr & " and your sports site has been set to {1}.", lp.NewsUrl, lp.SportsUrl)
            End If
            lp.GetIsoStoreInfo()
            Console.WriteLine("Enter 'd' to delete the IsolatedStorage files and exit, or press any other key to exit without deleting files.")
            Dim consoleInput As String = Console.ReadLine()
            If consoleInput.ToLower() = "d" Then
                lp.DeleteFiles()
                lp.DeleteDirectories()
            End If
        End Sub 'Main


        Shared Sub GatherInfoFromUser(ByVal lp As LoginPrefs)
            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()
        End Sub 'GatherInfoFromUser
    End Class 'ConsoleApp
    _

    Public Class LoginPrefs

        Public Sub New(ByVal myUserName As String)
            userName = myUserName
            myNewPrefs = GetPrefsForUser()
        End Sub 'New
        Private userName As String

        Private myNewsUrl As String

        Public Property NewsUrl() As String
            Get
                Return myNewsUrl
            End Get
            Set(ByVal Value As String)
                myNewsUrl = value
            End Set
        End Property
        Private mySportsUrl As String

        Public Property SportsUrl() As String
            Get
                Return mySportsUrl
            End Get
            Set(ByVal Value As String)
                mySportsUrl = value
            End Set
        End Property
        Private myNewPrefs As Boolean

        Public ReadOnly Property NewPrefs() As Boolean
            Get
                Return myNewPrefs
            End Get
        End Property

        Private Function GetPrefsForUser() As Boolean
            Try

                ' Retrieve an IsolatedStorageFile for the current Domain and Assembly.
                Dim isoFile As IsolatedStorageFile = _
                    IsolatedStorageFile.GetStore(IsolatedStorageScope.User _
                    Or IsolatedStorageScope.Assembly _
                    Or IsolatedStorageScope.Domain, Nothing, Nothing)

                Dim isoStream As New IsolatedStorageFileStream(Me.userName, FileMode.Open, _
                    FileAccess.Read, FileShare.Read)

                ' We only get this far 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

                    Dim aFileHandle As IntPtr = isoStream.Handle
                    Console.WriteLine(("A pointer to a file handle has been obtained. " & aFileHandle.ToString() & " " & aFileHandle.GetHashCode()))

                Catch ex As Exception
                    ' Handle the exception.
                    Console.WriteLine("Expected exception")
                    Console.WriteLine(ex.ToString())
                End Try

                Dim reader As New StreamReader(isoStream)
                ' Read the data.
                Me.NewsUrl = reader.ReadLine()
                Me.SportsUrl = reader.ReadLine()
                reader.Close()
                isoFile.Close()
                Return False
            Catch ex As System.IO.FileNotFoundException
                ' Expected exception if a file cannot be not found. This indicates that we have a new user.
                Return True
            End Try
        End Function 'GetPrefsForUser

        Public Function GetIsoStoreInfo() As Boolean
            Try
                'Get a User store with type evidence for the current Domain and the Assembly.
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))

                Dim dirNames As [String]() = isoFile.GetDirectoryNames("*")
                Dim fileNames As [String]() = isoFile.GetFileNames("*")
                Dim name As String

                ' List directories currently in this Isolated Storage.
                If dirNames.Length > 0 Then

                    For Each name In dirNames
                        Console.WriteLine("Directory Name: " & name)
                    Next name
                End If

                ' 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 Then

                    For Each name In fileNames
                        Console.WriteLine("File Name: " & name)
                    Next name
                End If

                isoFile.Close()
                Return True
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Function 'GetIsoStoreInfo

        Public Function SetPrefsForUser() As Double
            Try
                Dim isoFile As IsolatedStorageFile
                isoFile = IsolatedStorageFile.GetUserStoreForDomain()

                ' Open or create a writable file.
                Dim isoStream As New IsolatedStorageFileStream(Me.userName, FileMode.OpenOrCreate, FileAccess.Write, isoFile)

                Dim writer As New StreamWriter(isoStream)
                writer.WriteLine(Me.NewsUrl)
                writer.WriteLine(Me.SportsUrl)
                ' Calculate the amount of space used to record the user's preferences.
                Dim d As Double = Convert.ToDouble(isoFile.CurrentSize) / Convert.ToDouble(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 ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Function 'SetPrefsForUser
        'ToDo:  Handle the exception.

        Public Sub DeleteFiles()
            Try
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))
                Dim name As String
                Dim dirNames As [String]() = isoFile.GetDirectoryNames("*")
                Dim fileNames As [String]() = 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 Then
                    For Each name In fileNames
                        ' Delete the files.
                        isoFile.DeleteFile(name)
                    Next name
                    'Confirm no files are left.
                    fileNames = isoFile.GetFileNames("*")
                End If
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Sub 'DeleteFiles

        Public Sub DeleteDirectories()
            Try
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))
                Dim name As String
                Dim dirNames As [String]() = isoFile.GetDirectoryNames("*")
                Dim fileNames As [String]() = isoFile.GetFileNames("Archive\*")
                ' Delete all the files currently in the Archive directory.
                If fileNames.Length > 0 Then
                    For Each name In fileNames
                        isoFile.DeleteFile(("Archive\" & name))
                    Next name
                    'Confirm no files are left.
                    fileNames = isoFile.GetFileNames("Archive\*")
                End If
                If dirNames.Length > 0 Then
                    For Each name In dirNames
                        ' Delete the the directories in the Isolated Storage.
                        ' This deletes the Archive directory, there should not be any others.
                        isoFile.DeleteDirectory(name)
                    Next name
                End If
                dirNames = isoFile.GetDirectoryNames("*")
                isoFile.Remove()
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Sub 'DeleteDirectories

        Public Function SetNewPrefsForUser() As Double
            Try
                Dim inputChar As Byte
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))

                ' If this is not a new user, archive the old preferences and 
                ' overwrite them using the new preferences.
                If Not Me.myNewPrefs Then
                    If isoFile.GetDirectoryNames("Archive").Length = 0 Then
                        isoFile.CreateDirectory("Archive")
                    Else

                        Dim source As New IsolatedStorageFileStream(Me.userName, FileMode.OpenOrCreate, isoFile)
                        Dim canWrite, canRead As Boolean
                        ' This is the stream from which data will be read.
                        If source.CanRead Then canRead = True Else canRead = False
                        Console.WriteLine("Is the source file readable? " & canRead)
                        Console.WriteLine("Creating new IsolatedStorageFileStream for Archive.")

                        ' Open or create a writable file with a maximum size of 10K.
                        Dim target As New IsolatedStorageFileStream("Archive\ " & Me.userName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 10240, isoFile)

                        ' This is the stream to which data will be written.
                        If target.CanWrite Then canWrite = True Else canWrite = False
                        Console.WriteLine("Is the target file writable? " & canWrite)
                        target.SetLength(0)  'rewind the target file

                        ' Stream the old file to a new file in the Archive directory.
                        If source.IsAsync And target.IsAsync Then
                            ' IsolatedStorageFileStreams cannot be asynchronous.  However, you
                            ' can use the asynchronous BeginRead and BeginWrite functions
                            ' with some possible performance penalty.
                            Console.WriteLine("IsolatedStorageFileStreams can not be asynchronous.")
                        Else
                            Console.WriteLine("Writing data to the new file.")
                            While source.Position < source.Length
                                inputChar = CByte(source.ReadByte())
                                target.WriteByte(inputChar)
                            End While

                            ' Determine the size of the IsolatedStorageFileStream
                            ' by checking its Length property.
                            Console.WriteLine(("Total Bytes Read: " & source.Length))
                        End If

                        ' After you have read and written to the streams, close them.    
                        target.Close()
                        source.Close()
                    End If
                End If

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

                '  Calculate the amount of space used to record this user's preferences.
                Dim d As Double = Convert.ToDouble(isoFile.CurrentSize) / Convert.ToDouble(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 ex As Exception
                Console.WriteLine(ex.ToString())
                Return 0.0
            End Try
        End Function 'SetNewPrefsForUser
    End Class 'LoginPrefs
End Namespace 'ISOCS

[C#] 
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Policy;

[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();
        }
    }

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

                // We only get this far 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
                {

                    IntPtr aFileHandle = isoStream.Handle;
                    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 not 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)
            {
                //ToDo:  Handle the exception.
                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());
            }

        }
        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 the directories in the Isolated Storage.
                        // This deletes the Archive directory, there should not be any others.
                        isoFile.DeleteDirectory(dirNames[i]);  
                    }
                }
                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 with a maximum size of 10K.
                        IsolatedStorageFileStream target =
                            new IsolatedStorageFileStream("Archive\\ " + this.userName,
                            FileMode.OpenOrCreate,
                            FileAccess.Write,
                            FileShare.Write,
                            10240,
                            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 can not 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;
            }
        }
    }


[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::IO::IsolatedStorage;
using namespace System::Security::Policy;

__gc public class LoginPrefs 
{
private:
   String* userName;
   String* newsUrl;
   String* sportsUrl;
   bool newPrefs;

public:
   bool GetPrefsForUser()
   {
      try 
      {

         // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
         IsolatedStorageFile* isoFile =
            IsolatedStorageFile::GetStore(
            static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | 
            IsolatedStorageScope::Assembly |
            IsolatedStorageScope::Domain),
            (Type*)0, 0);
         IsolatedStorageFileStream* isoStream = new IsolatedStorageFileStream(this->userName,
            FileMode::Open,  
            FileAccess::ReadWrite,
            isoFile);

         // We only get this far 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
         {

            IntPtr aFileHandle = isoStream->Handle;
            Console::WriteLine(S"A pointer to a file handle has been obtained. {0} {1}",
               __box(aFileHandle), __box(aFileHandle.GetHashCode()));
         }

         catch (Exception* e) 
         {
            // Handle the exception.
            Console::WriteLine(S"Expected exception");
            Console::WriteLine(e->ToString());
         }

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

      String* dirNames[]  = isoFile->GetDirectoryNames(S"*");
      String* fileNames[] = isoFile->GetFileNames(S"*");

      // List directories currently in this Isolated Storage.
      if (dirNames->Length>0)
      {
         for (int i=0;i<dirNames->Length;++i) 
         {
            Console::WriteLine(S"Directory Name: {0}", 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(S"File Name: {0}", fileNames[i]);
         }
      }

      isoFile->Close();
      return true;
   }

   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(S"CurrentSize = {0}", isoFile->CurrentSize.ToString());
         Console::WriteLine(S"MaximumSize = {0}", isoFile->MaximumSize.ToString());
         writer->Close();
         isoFile->Close();
         isoStream->Close();
         return d;
      }
      catch (Exception* e) //(IsolatedStorageException*)
      {
         //ToDo:  Handle the exception.
         Console::WriteLine(e->ToString());
         return 0.0;
      }
   }

   void DeleteFiles ()
   {
      try
      {
         IsolatedStorageFile* isoFile = IsolatedStorageFile::GetStore(
            static_cast<IsolatedStorageScope>(IsolatedStorageScope::User |
            IsolatedStorageScope::Assembly |
            IsolatedStorageScope::Domain),
            __typeof(System::Security::Policy::Url),
            __typeof(System::Security::Policy::Url));

         String* dirNames[]  = isoFile->GetDirectoryNames(S"*");
         String* fileNames[] = isoFile->GetFileNames(S"*");

         // 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(S"*");
         }
         isoFile->Close();
      }
      catch (Exception* e)
      {
         Console::WriteLine(e->ToString());
      }

   }
   void DeleteDirectories()
   {
      try
      {
         IsolatedStorageFile* isoFile = IsolatedStorageFile::GetStore(
            static_cast<IsolatedStorageScope>(IsolatedStorageScope::User |
            IsolatedStorageScope::Assembly |
            IsolatedStorageScope::Domain),
            __typeof(System::Security::Policy::Url),
            __typeof(System::Security::Policy::Url));

         String* dirNames[]  = isoFile->GetDirectoryNames(S"*");
         String* fileNames[] = isoFile->GetFileNames(S"Archive\\*");

         // Delete the current files within the Archive directory.

         if (fileNames->Length>0)
         {
            for (int i=0;i<fileNames->Length;++i) 
            {
               //delete files
               isoFile->DeleteFile((S"Archive\\{0}", fileNames[i]));
            }
            //Confirm no files are left.
            fileNames = isoFile->GetFileNames(S"Archive\\*");
         }


         if (dirNames->Length>0)
         {
            for (int i=0; i<dirNames->Length; ++i) 
            {
               // Delete the the directories in the Isolated Storage.
               // This deletes the Archive directory, there should not be any others.
               isoFile->DeleteDirectory(dirNames[i]);  
            }
         }
         dirNames = isoFile->GetDirectoryNames(S"*");
         isoFile->Remove();
      }
      catch (Exception* e)
      {
         Console::WriteLine(e->ToString());
      }

   }
   double SetNewPrefsForUser ()
   {
      try
      {
         Byte inputChar;
         IsolatedStorageFile* isoFile = IsolatedStorageFile::GetStore(
            static_cast<IsolatedStorageScope>(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->NewPrefs)
         {
            if ( isoFile->GetDirectoryNames(S"Archive")->Length == 0 )
               isoFile->CreateDirectory(S"Archive");
            else
            {
               // This is the stream to which data will be written.
               IsolatedStorageFileStream* source =
                  new IsolatedStorageFileStream(this->userName,FileMode::OpenOrCreate,
                  isoFile);
               // This is the stream from which data will be read.
               Console::WriteLine(S"Is the source file readable?  {0}", (source->CanRead ? S"true" : S"false"));
               Console::WriteLine(S"Creating new IsolatedStorageFileStream for Archive.");

               // Open or create a writable file with a maximum size of 10K.
               IsolatedStorageFileStream* target =
                  new IsolatedStorageFileStream((S"Archive\\ {0}", this->userName),
                  FileMode::OpenOrCreate,
                  FileAccess::Write,
                  FileShare::Write,
                  10240,
                  isoFile);

               Console::WriteLine(S"Is the target file writable? {0}", (target->CanWrite ? S"true" : S"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(S"IsolatedStorageFileStreams can not be asynchronous.");
               }
               else
               {
                  Console::WriteLine(S"Writing data to the new file.");
                  while (source->Position < source->Length)
                  {
                     inputChar = (Byte)source->ReadByte();
                     target->WriteByte((Byte)source->ReadByte());
                  }

                  // Determine the size of the IsolatedStorageFileStream
                  // by checking its Length property.
                  Console::WriteLine(S"Total Bytes Read: {0}", source->Length.ToString());

               }

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

         // Open or create a writable file, no larger than 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(S"CurrentSize = {0}", isoFile->CurrentSize.ToString());
         Console::WriteLine(S"MaximumSize = {0}", isoFile->MaximumSize.ToString());
         // StreamWriter.Close implicitly closes isoStream.
         writer->Close();
         isoFile->Close();

         return d;
      }
      catch (Exception* e)
      {
         Console::WriteLine(e->ToString());
         return 0.0;
      }
   }
   LoginPrefs(String* aUserName) 
   {
      userName = aUserName;
      newPrefs = GetPrefsForUser();
   }

   __property String* get_NewsUrl() 
   {
      return newsUrl; 
   }

   __property void set_NewsUrl(String* value) 
   {
      newsUrl = value;
   }
   __property String* get_SportsUrl() {
      return sportsUrl;
   }

   __property void set_SportsUrl(String* value) 
   {
      sportsUrl = value;
   }

   __property bool get_NewPrefs() 
   {
      return newPrefs;
   }
};
void GatherInfoFromUser (LoginPrefs* lp )
{
   Console::WriteLine(S"Please enter the URL of your news site.");
   lp->NewsUrl = Console::ReadLine();
   Console::WriteLine(S"Please enter the URL of your sports site.");
   lp->SportsUrl = Console::ReadLine();
}

int main() 
{

   // Prompt the user for their username.

   Console::WriteLine(S"Enter your login ID:");

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

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

      // Write the new preferences to storage.
      double percentUsed = lp->SetPrefsForUser();
      Console::WriteLine(S"Your preferences have been written. Current space used is {0}%", __box(percentUsed));
   }
   else 
   {
      Console::WriteLine(S"Welcome back.");

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

      Console::WriteLine(S"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(S"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->Equals(S"d"))
   {
      lp->DeleteFiles();
      lp->DeleteDirectories();
   }


}

//}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.IO.IsolatedStorage

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

IsolatedStorageFile メンバ | System.IO.IsolatedStorage 名前空間