You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Platform Uno下Android平台SD卡写入权限申请与写入方法咨询

在Platform Uno中实现Android平台SD卡写入操作的完整指南

嗨,JaFu0815!我来帮你搞定Platform Uno里Android SD卡写入的问题——毕竟常规内部存储和可移除SD卡的权限、路径逻辑确实不一样,咱一步步来:

一、先搞定权限配置(静态+动态)

Android对外部存储的权限管控很严,得先把权限配置到位:

1. 静态配置Android清单权限

在你的Uno项目的Android平台项目里,找到AndroidManifest.xml,添加以下权限声明:

<!-- 基础写入权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 针对Android 10+的兼容配置,绕过Scoped Storage限制(如果需要访问公共目录) -->
<application android:requestLegacyExternalStorage="true" ...>

如果你的目标是Android 11+,还得考虑Scoped Storage的规则,后面会提到。

2. 动态申请权限(Android 6.0+必备)

因为Android 6.0(API 23)及以上,危险权限需要在运行时动态申请,不能只靠清单。在Uno的共享代码里,添加权限请求逻辑:

using Uno.UI;
using Microsoft.Maui.ApplicationModel;

// 比如在按钮点击事件里触发权限申请
private async Task RequestStoragePermission()
{
    var status = await Permissions.RequestAsync<Permissions.StorageWrite>();
    if (status != PermissionStatus.Granted)
    {
        // 权限被拒绝,提示用户去设置开启
        await Application.Current.MainPage.DisplayAlert("权限提示", "需要SD卡写入权限才能完成操作,请前往设置开启", "知道了");
        return;
    }
    // 权限通过,执行写入操作
    await WriteToSdCard();
}

二、获取SD卡的有效路径

Android的SD卡路径不是固定的,别硬编码!推荐用系统API获取:

using Android.OS;
using Android.Content;

private string GetSdCardPath()
{
    // 获取所有外部存储目录(包括内部存储和SD卡)
    var externalDirs = Android.App.Application.Context.GetExternalFilesDirs(null);
    foreach (var dir in externalDirs)
    {
        if (dir != null && !Android.OS.Environment.IsExternalStorageEmulated(dir))
        {
            // 这就是可移除SD卡的路径(对应APP专属目录,无需额外权限)
            return dir.AbsolutePath;
        }
    }
    // 如果没找到SD卡, fallback到公共外部存储
    return Android.OS.Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDocuments).AbsolutePath;
}

注意:如果要写入SD卡的公共目录(比如根目录、Downloads),在Android 11+下即使有WRITE_EXTERNAL_STORAGE权限也不行,得用MediaStore API来操作。

三、实现SD卡写入操作

权限和路径都搞定后,就可以写文件了,和常规文件操作类似:

private async Task WriteToSdCard()
{
    var sdCardPath = GetSdCardPath();
    var targetFilePath = Path.Combine(sdCardPath, "test_sd_file.txt");
    
    try
    {
        var content = "这是写入SD卡的测试内容!";
        await File.WriteAllTextAsync(targetFilePath, content);
        await Application.Current.MainPage.DisplayAlert("成功", "文件已写入SD卡", "好的");
    }
    catch (Exception ex)
    {
        await Application.Current.MainPage.DisplayAlert("错误", $"写入失败:{ex.Message}", "确定");
    }
}

四、Android 11+的特殊注意事项

如果你的APP目标是Android 11(API 30)及以上,Scoped Storage会限制直接访问SD卡的公共目录:

  • 如果只是写入APP专属的SD卡目录(就是上面GetSdCardPath返回的路径),不需要额外操作,权限足够;
  • 如果要写入公共目录(比如Downloads、Pictures),得用MediaStore API来插入文件,而不是直接用File类。

内容的提问来源于stack exchange,提问作者popsicle7500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:37:39