Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 58056

Installing an exisiting database from Assets in Android: Here's How

$
0
0

To copy an existing database from the /Assets folder to a writeable location, you can use this:

using System;
using System.IO;
using Common.Android.Dependencies;
using Common.Interfaces;
using Xamarin.Forms;

[assembly: Dependency(typeof(FileCopy))]
namespace Common.Android.Dependencies
{
    public class FileCopy :IFileCopy
    {
        public void InstallDatabase(string databaseName)
        {
            var docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var dbFile = Path.Combine(docFolder, databaseName); // FILE NAME TO USE WHEN COPIED
            if (!File.Exists(dbFile))
            {
                FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write);
                ReadWriteStream(Forms.Context.Assets.Open(databaseName), writeStream);
            }
        }

        private void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = readStream.Read(buffer, 0, Length);                     
            // write the required bytes
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, Length);
            }
            readStream.Close();
            writeStream.Close();
        }
    }
}

Viewing all articles
Browse latest Browse all 58056

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>