0

My application records data from a patient monitor and stores it a '*.dat' file in 'Environment.SpecialFolder.Personal'.

The app also allows the user to 'play back' previously acquired recordings.

I wish to include a few sample 'dat' files within the apk. Is it possible to include such files as 'assets' in the project and have them copied to 'Environment.SpecialFolder.Personal' at the time of installation?

Andy Pybus
  • 21
  • 2

1 Answers1

0

Copy the database into Assets folder.

enter image description here

And set the Build Action as AndroidAssect.

enter image description here

You could use the following code to copy the file from Assects folder to Android Application folder.

// Android application default folder.
        var appFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var dbFile = Path.Combine(appFolder, "database.db3");

        // Check if the file already exists.
        if (!File.Exists(dbFile))
        {
            using (FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
            {
                // Assets is comming from the current context.
                await Assets.Open(databaseName).CopyToAsync(writeStream);
            }
        }

Download the source file from the link below. https://github.com/damienaicheh/CopyAssetsProject

Updated:

You could use the code below.

var assetName = "someasset.jpg";
var outputName = Path.Combine(Android.OS.Environment.DirectoryDownloads, 
assetName);
using (var assetStream = context.Assets.Open(assetName))
using (var fileStream = new FileStream(outputName, FileMode.CreateNew))
{
await assetStream.CopyToAsync(fileStream);
}

If your device is higher than Android6.0, you need runtime permission. https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/android-m-runtimepermissions/

For more details, please refer to the link below. How to save file from assets on my device? Xamarin

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
Wendy Zang - MSFT
  • 10,509
  • 1
  • 7
  • 17
  • I'd just arrived at the same solution! I don't suppose how you can tell me how copy the asset (file) to the external SD Card in Xamarin Forms (Android) as well? – Andy Pybus Nov 15 '19 at 04:00
  • Any update? Have you solved your problem? If the reply help you, do not forget to acept the answer. – Wendy Zang - MSFT Nov 28 '19 at 09:19