如何:在独立存储中读取和写入文件
若要读取或写入独立存储区的文件,请使用包含流读取器(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