Created
January 21, 2017 01:46
-
-
Save 3t14/df358cd9716add3f4eed73d9de7ddf87 to your computer and use it in GitHub Desktop.
ローカルストレージに対する共通ファイルアクセス方法の例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using PCLStorage; | |
using Xamarin.Forms; | |
namespace HelloPCLStorage | |
{ | |
public class App : Application | |
{ | |
private Entry usernameEntry; | |
public App() | |
{ | |
var saveButton = new Button | |
{ | |
Text = "保存" | |
}; | |
usernameEntry = new Entry | |
{ | |
Placeholder = "Username" | |
}; | |
// The root page of your application | |
var content = new ContentPage | |
{ | |
Title = "HelloPCLStorage", | |
Content = new StackLayout | |
{ | |
VerticalOptions = LayoutOptions.Center, | |
Children = { | |
new Label { | |
HorizontalTextAlignment = TextAlignment.Center, | |
Text = "Welcome to Xamarin Forms!" | |
}, | |
usernameEntry, | |
saveButton | |
} | |
} | |
}; | |
saveButton.Clicked += async (sender, e) => | |
{ | |
await SaveSettings(); | |
}; | |
MainPage = new NavigationPage(content); | |
} | |
private string settingsFilename = "settings.dat"; | |
public async Task LoadSettings() | |
{ | |
// 保存先のフォルダインスタンスを生成 | |
IFolder rootFolder = FileSystem.Current.LocalStorage; | |
ExistenceCheckResult result = await rootFolder.CheckExistsAsync(settingsFilename); | |
switch (result) | |
{ | |
case ExistenceCheckResult.FileExists: | |
// 存在する時だけ取得反映 | |
IFile file = await rootFolder.GetFileAsync(settingsFilename); | |
usernameEntry.Text = await file.ReadAllTextAsync(); | |
break; | |
case ExistenceCheckResult.FolderExists: | |
case ExistenceCheckResult.NotFound: | |
default: | |
break; | |
} | |
} | |
public async Task SaveSettings() | |
{ | |
// 保存先のフォルダインスタンスを生成 | |
IFolder rootFolder = FileSystem.Current.LocalStorage; | |
// 保存先のファイルを開く(存在いている場合は上書き | |
IFile file = await rootFolder.CreateFileAsync(settingsFilename, | |
CreationCollisionOption.ReplaceExisting); | |
// 単一項目のみなので、文字列をそのまま保存 | |
await file.WriteAllTextAsync(usernameEntry.Text); | |
} | |
protected override async void OnStart() | |
{ | |
// Handle when your app starts | |
await LoadSettings(); | |
} | |
protected override void OnSleep() | |
{ | |
// Handle when your app sleeps | |
} | |
protected override void OnResume() | |
{ | |
// Handle when your app resumes | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment