Skip to content

Instantly share code, notes, and snippets.

@nuitsjp
Created November 17, 2016 23:25
Show Gist options
  • Save nuitsjp/cd7997b8441d30498e936c777ec00e0a to your computer and use it in GitHub Desktop.
Save nuitsjp/cd7997b8441d30498e936c777ec00e0a to your computer and use it in GitHub Desktop.
Use embedded sqlite database file in Xamarin.Forms
const string databaseFileName = "sqlite.db3";
// ルートフォルダを取得する
IFolder rootFolder = FileSystem.Current.LocalStorage;
// ファイルシステム上のDBファイルの存在チェックを行う
var result = await rootFolder.CheckExistsAsync(databaseFileName);
if (result == ExistenceCheckResult.NotFound)
{
// 存在しなかった場合、新たに空のDBファイルを作成する
var newFile = await rootFolder.CreateFileAsync(databaseFileName, CreationCollisionOption.ReplaceExisting);
// Assemblyに埋め込んだDBファイルをストリームで取得し、空ファイルにコピーする
var assembly = typeof(App).GetTypeInfo().Assembly;
using (var stream = assembly.GetManifestResourceStream("XFEmbeddSQLiteFile.sqlite.db3"))
{
using (var outputStream = await newFile.OpenAsync(FileAccess.ReadAndWrite))
{
stream.CopyTo(outputStream);
outputStream.Flush();
}
}
}
// ファイルからコネクションを作成しデータを取得する
var file = await rootFolder.CreateFileAsync(databaseFileName, CreationCollisionOption.OpenIfExists);
using (var connection = new SQLiteConnection(file.Path))
{
var builder = new StringBuilder();
foreach (var customer in connection.Table<Customer>())
{
builder.Append($"Id:{customer.Id} Name:{customer.Name}, ");
}
label.Text = builder.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment