共用方式為


作法:讀取和寫入隔離儲存區中的檔案

若要在隔離存放區中的檔案內進行讀取或寫入,請使用具有資料流讀取器 (IsolatedStorageFileStream 物件) 或資料流寫入器 (StreamReader 物件) 的 StreamWriter 物件。

範例

下列程式碼範例會取得隔離存放區,並檢查存放區中是否存在名為 TestStore.txt 的檔案。 如果不存在,它會建立檔案,並將 "Hello Isolated Storage" 寫入檔案。 如果 TestStore.txt 已經存在,程式碼範例會從檔案讀取。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

            if (isoStore.FileExists("TestStore.txt"))
            {
                Console.WriteLine("The file already exists!");
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.Open, isoStore))
                {
                    using (StreamReader reader = new StreamReader(isoStream))
                    {
                        Console.WriteLine("Reading contents:");
                        Console.WriteLine(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew, isoStore))
                {
                    using (StreamWriter writer = new StreamWriter(isoStream))
                    {
                        writer.WriteLine("Hello Isolated Storage");
                        Console.WriteLine("You have written to the file.");
                    }
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.IsolatedStorage

Module Module1

    Sub Main()
        Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or IsolatedStorageScope.Assembly, Nothing, Nothing)

        If (isoStore.FileExists("TestStore.txt")) Then
            Console.WriteLine("The file already exists!")
            Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("TestStore.txt", FileMode.Open, isoStore)
                Using reader As StreamReader = New StreamReader(isoStream)
                    Console.WriteLine("Reading contents:")
                    Console.WriteLine(reader.ReadToEnd())
                End Using
            End Using
        Else
            Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew, isoStore)
                Using writer As StreamWriter = New StreamWriter(isoStream)
                    writer.WriteLine("Hello Isolated Storage")
                    Console.WriteLine("You have written to the file.")
                End Using
            End Using
        End If
    End Sub

End Module

另請參閱