windows phone的所有檔案IO操作都被限制在隔離儲存空間中(IsolatedStorage),因此一個應用程式是不能訪問註冊表和其他應用程式內容的。雖然限制很多,但這樣也對手機安全和規範起到了很好的作用。
WP7中的隔離儲存空間是沒有大小限制的,可以無限制的使用空間,但最好能把資料同步到雲端,減少本機存放區。
我們在隔離儲存空間中可以增加、刪除、修改檔案和目錄,也可以在隔離儲存空間中儲存程式配置的資訊。
隔離儲存空間用到3個重要的類:
IsolatedStorageFile:用來操控隔離儲存空間裡面的目錄以及檔案;
IsolatedStorageFileStream:用於讀寫隔離儲存空間裡面的檔案流;
IsolatedStorageSettings:用於儲存配置資訊的Dictionary。
首先如果我們要使用隔離儲存空間需要引用兩個命名空間:
using System.IO;
using System.IO.IsolatedStorage;
1、目錄操作
(1)新增目錄
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(folderName))
{
MessageBox.Show("已經存在目錄" + folderName+ ",無法建立!");
}
else
{
isoFile.CreateDirectory(folderName);
MessageBox.Show("建立成功!");
}
}
(2)檢查目錄是否存在
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if(isoFile.DirectoryExists(folderName))
{
MessageBox.Show("存在目錄" + folderName);
}
else
{
MessageBox.Show("不存在目錄" + folderName);
}
}
(3)刪除目錄
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(folderName))
{
isoFile.DeleteDirectory(folderName);
MessageBox.Show(folderName+ "已成功刪除!");
}
else
{
MessageBox.Show("不存在目錄" + folderName);
}
}
2、檔案操作
(1)新增檔案
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
FileStream fileStream = isoFile.CreateFile(fileName);
fileStream.Close();
}
(2)檢查檔案是否存在
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(fileName))
{
MessageBox.Show("存在檔案" + fileName);
}
else
{
MessageBox.Show("不存在檔案" + fileName);
}
}
(3)刪除檔案
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
isoFile.DeleteFile(fileName);
}
3、檔案讀寫
(1)寫檔案
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoFileStream = isoFile.OpenFile(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
StreamWriter streamWriter = new StreamWriter(isoFileStream);
streamWriter.WriteLine(ContentTextBox.Text);
streamWriter.Close();//very importent
}
}
(2)讀檔案
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoFileStream = isoFile.OpenFile(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
StreamReader streamReader = new StreamReader(isoFileStream);
ContentTextBox.Text = streamReader.ReadToEnd().ToString();
streamReader.Close();
}
}
4、通過IsolatedStorageSettings類來儲存和讀取配置
(1)寫配置
IsolatedStorageSettings.ApplicationSettings[settingName] = SettingTextBox.Text;
IsolatedStorageSettings.ApplicationSettings.Save();//very importent.
(2)讀配置
if (IsolatedStorageSettings.ApplicationSettings.Contains(settingName))
{
SettingTextBox.Text = IsolatedStorageSettings.ApplicationSettings[settingName] as string;
}
擴充閱讀:http://www.cnblogs.com/zdave/archive/2011/06/01/2067282.html
http://www-congci-com/item/isolatedstorage-wp7-app-data