c# - How to get all available storages paths in Xamarin Forms?
问题描述
I'm trying to get all the available media files -Or files with specific extensions- in the device -Either Android or IOS- but I can't find a way to do this, so instead I was trying to get all the device storages and I'll iterate through them with my own code to get the files I need.
However, I can't find a way to get the storages paths as well, but I know I get the main storage path in Android using Android.OS.Environment.ExternalStorageDirectory.AbsolutePath
so maybe I can make an interface for the same for IOS, but still, that gets the main storage only, not any attached USB or Memory Cards...
So any help would be appreciated in either approaches. Thanks in advance.
解决方案
安卓:
Android 将文件系统分为两种不同类型的存储:内部存储、外部存储。
内部存储: https ://docs.microsoft.com/en-us/xamarin/android/platform/files/#working-with-internal-storage
您可以使用System.Environment.GetFolderPath()
检索内部存储目录,如下所示:
/data/user/0/com.companyname/files
外部存储:https ://docs.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
私有外部文件的目录将是:
/storage/emulated/0/Android/data/com.companyname.app/files/
您可以通过依赖服务获取它。
DependencyService:https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/app- basics/dependency-service/introduction
创建接口 IExternalStorage:
public interface IExternalStorage
{
string GetPath();
}
Android上的实现:
[assembly:Dependency(typeof(AndroidImplementation))]
namespace App.Droid
{
public class AndroidImplementation: IExternalStorage
{
public string GetPath()
{
Context context = Android.App.Application.Context;
var filePath = context.GetExternalFilesDir("");
return filePath.Path;
}
}
}
然后你可以在 Xamarin.Forms 中使用它:
var folderPath = DependencyService.Get<IExternalStorage>(). GetPath();
IOS:
每个 iOS 应用程序都有自己的沙箱目录。https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
通常,我们将用户的数据存储在 Documents 文件夹中。我们可以直接在 Forms 上访问它的路径:
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
请注意:IOS 只能访问照片库和 iCloud 文件夹。
Xamarin.iOS 中的文件系统访问:https ://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/file-system
推荐阅读
- ruby-on-rails - Rail6 db:migrate 失败 - 参数数量错误(给定 1,预期 0)
- sql - 为什么 select with subselect 在条件下不返回任何行的速度要慢得多?
- spring - 在spring boot中使用pageable获取和删除对象
- php - 页脚没有取代它的位置
- java - SAP Hybris 无法创建自定义横幅组件
- c# - JSON 中的动态键
- java - 从 PDF 剥离器转置矩阵
- perl - Perl grep 通过大文件匹配字符串
- azure - 如何使用 Azure Devops 将 powershell 列表变量传输到 terraform?
- python - 仅将列表拆分为数字