Skip to content

Instantly share code, notes, and snippets.

@nuitsjp

nuitsjp/sample.cs

Created Nov 17, 2016
Embed
What would you like to do?
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
You can’t perform that action at this time.