简体   繁体   中英

Xamarin.Forms.Android: Populating 'Environment.SpecialFolder.Personal' with sample data files at compilation/deployment

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?

Copy the database into Assets folder.

在此处输入图像描述

And set the Build Action as AndroidAssect.

在此处输入图像描述

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://docs.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM