简体   繁体   English

Xamarin.Forms.Android:在编译/部署时使用示例数据文件填充“Environment.SpecialFolder.Personal”

[英]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'.我的应用程序记录来自患者监视器的数据,并将其存储在“Environment.SpecialFolder.Personal”中的“*.dat”文件中。

The app also allows the user to 'play back' previously acquired recordings.该应用程序还允许用户“回放”以前获得的录音。

I wish to include a few sample 'dat' files within the apk.我希望在 apk 中包含一些示例“dat”文件。 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?是否可以在项目中包含“资产”等文件,并在安装时将它们复制到“Environment.SpecialFolder.Personal”?

Copy the database into Assets folder.将数据库复制到 Assets 文件夹中。

在此处输入图像描述

And set the Build Action as AndroidAssect.并将 Build Action 设置为 AndroidAssect。

在此处输入图像描述

You could use the following code to copy the file from Assects folder to Android Application folder.您可以使用以下代码将文件从 Assects 文件夹复制到 Android Application 文件夹。

// 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 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.如果您的设备高于 Android6.0,则需要运行时权限。 https://docs.microsoft.com/en-us/samples/xamarin/monodroid-samples/android-m-runtimepermissions/ 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 Xamarin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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