[Xamarin] 透過 IsolatedStorageFile儲存資料
2013-07-15
開發手機App通常都會遇到想要儲存資料的,舉個例來說,像是
(圖片來源:http://docs.xamarin.com/guides/android/application_fundamentals/activity_lifecycle)
在android 生命週期中,OnReusme 可能需要把上次狀態讀取出來,在OnStop中因為App被中斷,所以必須把現在狀態寫起來
以方便還原,這時候就會用到這儲存的機制..
看一下官方文件: http://docs.xamarin.com/guides/cross-platform/application_fundamentals/building_cross_platform_applications/part_5_-_practical_code_sharing_strategies
他直接連結到MSDN-Isolated Storage Overview for Windows Phone 那不就等於方便到爆炸,直接拿Windows Phone 的Code就可以用了..
來介紹一下今天範例..
按下儲存資料(btnSave1)的時候,就將EditView(editTextMain)資料寫入,
按下讀取資料(btnRead1)時就會將寫入的資料讀取出來,因為是範例,所以盡量單純點..直接來看Code
儲存資料:
var btnSave1 = FindViewById<Button>(Resource.Id.btnSave1);
btnSave1.Click += delegate
{IsolatedStorageFile storageFiles = IsolatedStorageFile.GetUserStoreForApplication();
//如果判斷已經有檔案就把它砍掉
if (storageFiles.FileExists("UserInfo/data.txt"))
{
storageFiles.DeleteFile("UserInfo/data.txt");
}
//建立檔案夾
storageFiles.CreateDirectory("UserInfo");
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("UserInfo/data.txt", FileMode.OpenOrCreate, storageFiles));
//寫入至目標
fileWriter.Write(editTextMain.Text);
fileWriter.Close();
storageFiles.Dispose();
Toast.MakeText(this, "Success Save", ToastLength.Short).Show();
};
var btnRead1 = FindViewById<Button>(Resource.Id.btnRead1);
btnRead1.Click += delegate
{
IsolatedStorageFile storageFiles = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader fileReader = null;
//判斷檔案是否存在
if (storageFiles.FileExists("UserInfo/data.txt"))
{
try
{
fileReader = new StreamReader(new IsolatedStorageFileStream("UserInfo/data.txt", FileMode.Open, storageFiles));
var result = fileReader.ReadToEnd();
Toast.MakeText(this, result, ToastLength.Long).Show();
fileReader.Close();
}
catch(Exception ex)
{
Toast.MakeText(this, "Error:"+ex.Message, ToastLength.Long).Show();
}
}
else
{
Toast.MakeText(this, "Error:" + "Sorry我找不到檔案喔!", ToastLength.Long).Show();
}
};
是不是整個跟在Windows Phone 上面開發經驗一致..真的是很溫馨..
reference:
http://www.dotblogs.com.tw/junegoat/archive/2011/01/24/silverlight-windows-phone7-isolatedstoragefile.aspx?fid=24197
http://docs.xamarin.com/guides/cross-platform/application_fundamentals/building_cross_platform_applications/part_5_-_practical_code_sharing_strategies
http://msdn.microsoft.com/zh-tw/library/ff402541(v=vs.92).aspx
Sample Code: