如何从设备上的资产中保存文件? Xamarin

时间:2018-07-15 20:20:06

标签: c# xamarin xamarin.android

我有一个拥有很多资产的程序。我想从我的应用程序中将其中之一保存在Android设备上的“下载”文件夹中。我该怎么办?

1 个答案:

答案 0 :(得分:1)

结合使用C#和Android Java框架,可以直接实现实际的文件副本:

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);
}

然后,您必须处理应用程序权限:

首先,您需要将权限添加到清单。您必须具有写访问权,但很可能还需要读访问权,以检查文件是否已存在于“下载”文件夹等中。

您可以通过Xamarin.Android应用程序项目选项(“构建” /“ Android应用程序” /“必需的权限”)执行此操作,或在清单中手动设置它们:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

但是,对于棉花糖及更高版本,您还需要在运行时询问用户是否允许该应用读取/写入设备的外部存储,请查看Xamarin的博客文章以了解详细信息:

快速/脏版本是您必须请求权限,然后等待这些结果来查看用户是否允许/拒绝该请求:

请求权限:

const string writePermission = Manifest.Permission.WriteExternalStorage;
const string readPermission = Manifest.Permission.ReadExternalStorage;
string[] PermissionsLocation =
 {
    writePermission, readPermission
 };
if ((ContextCompat.CheckSelfPermission(this, writePermission) == Permission.Granted) && (ContextCompat.CheckSelfPermission(this, readPermission) == Permission.Granted))
{
    // You already have permission, so copy your files...
}
if (ActivityCompat.ShouldShowRequestPermissionRationale(this, writePermission) && (ContextCompat.CheckSelfPermission(this, readPermission) == Permission.Granted))
{
    // Displaying a dialog would make sense, but for an example this works...
    Toast.MakeText(this, "Will need permission to copy files to your Downloads folder", ToastLength.Long).Show();
    return;
}
ActivityCompat.RequestPermissions(this, PermissionsLocation, 999);

处理请求的结果:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    switch (requestCode)
    {
        case 999:
            if (grantResults[0] == Permission.Granted)
            {
                // you have permission, you are allowed to read/write to external storage go do it...
            }
            break;
        default:
            break;
    }
}