首页 > 解决方案 > 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.

标签: c#xamlxamarin.formsfile-iomedia

解决方案


安卓:

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


推荐阅读