[Xamarin] 透過 IsolatedStorageFile儲存資料

2013-07-15

開發手機App通常都會遇到想要儲存資料的,舉個例來說,像是
2013-07-15_155114
(圖片來源: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

2013-07-15_155430

他直接連結到MSDN-Isolated Storage Overview for Windows Phone 那不就等於方便到爆炸,直接拿Windows Phone 的Code就可以用了..
來介紹一下今天範例..
Screenshot_2013-07-15-15-46-44222
按下儲存資料(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();
    }

};
結果:
Screenshot_2013-07-15-15-46-40

Screenshot_2013-07-15-15-46-44

是不是整個跟在Windows Phone 上面開發經驗一致..真的是很溫馨..


當麻許的超技八 2014 | Donma Hsu Design.