2
votes

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..

https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows

Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms

2

2 Answers

3
votes

There is none I can think of. With netstandard everything is way more simple as you can use the classic c# File api to get the folders.

You just have to know the mappings between special folders and android folders (per example):

System.Environment.SpecialFolder    Path
ApplicationData                     INTERNAL_STORAGE/.config
Desktop                             INTERNAL_STORAGE/Desktop
LocalApplicationData                INTERNAL_STORAGE/.local/share
MyDocuments                         INTERNAL_STORAGE
MyMusic                             INTERNAL_STORAGE/Music
MyPictures                          INTERNAL_STORAGE/Pictures
MyVideos                            INTERNAL_STORAGE/Videos
Personal                            INTERNAL_STORAGE

source: https://docs.microsoft.com/en-US/xamarin/android/platform/files/

same for ios:

https://docs.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system

But it's really easy to implement, just enumerate all folders and display them in a ListView.

EDIT: more details on implementation.

In fact you want to code a "directory explorer", it's easy, here is the concept.

  • You have a ListView in your Page
  • You have a Cancel button and a Select button in your Page
  • You have a CurrentPath in your ViewModel
  • You bind CurrentPath to the Title of your Page
  • You have an List<DirectoryViewModel> Directories in your ViewModel

Each time a user click on a item from the list:

  • You add the directory name in your current path
  • You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
  • The ListView will be updated accordingly

Each time you back:

  • You remove last part of your current path
  • same as before

If you arrive to root path "/", you do nothing when clicking on back.

Oh and you could use this Grid component to instead of the ListView, will be nicer ;)

https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout

0
votes

You can edit this to make it work..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Util;

namespace Android.Basic.IO
{
    
    public class DirectoryPicker : ListActivity
    {


        public const String START_DIR = "startDir";
        public const String ONLY_DIRS = "onlyDirs";
        public const String SHOW_HIDDEN = "showHidden";
        public const String CHOSEN_DIRECTORY = "chosenDir";
        public const int PICK_DIRECTORY = 43522;
        private File dir;
        private Boolean showHidden = false;
        private bool onlyDirs = true;
        public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
        {
            base.OnCreate(savedInstanceState, persistentState);
            Bundle extras = Intent.Extras;
            dir = OS.Environment.ExternalStorageDirectory;
            if (extras != null)
            {
                String preferredStartDir = extras.GetString(START_DIR);
                showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
                onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
                if (preferredStartDir != null)
                {
                    File startDir = new File(preferredStartDir);
                    if (startDir.IsDirectory)
                    {
                        dir = startDir;
                    }
                }
            }

            SetContentView(Resource.Layout.folder_chooser_activity);
            var title = dir.AbsolutePath.ToString();
            Title = (title);
            Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
            String name = dir.Name;
            if (name.Length == 0)
                name = "/";
            btnChoose.Text = ("Choose " + "'" + name + "'");
            btnChoose.Click += delegate
              {
                  returnDir(dir.AbsolutePath);
              };
            ListView lv = this.ListView;
            lv.TextFilterEnabled = (true);

            if (!dir.CanRead())
            {
                Context context = ApplicationContext;
                String msg = "Could not read folder contents.";
                Toast.MakeText(context, msg, ToastLength.Long).Show();
                return;
            }
            var files = filter(dir.ListFiles(), onlyDirs, showHidden);
            String[] names = Names(files);
            ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
            lv.ItemClick += (ff, gg) =>
            {
                var position = gg.Position;
                if (!files[gg.Position].IsDirectory)
                    return;
                String path = files[position].AbsolutePath;
                var intent = new Intent(this, typeof(DirectoryPicker));
                intent.PutExtra(DirectoryPicker.START_DIR, path);
                intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
                intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
                StartActivityForResult(intent, PICK_DIRECTORY);
            };

        }

        protected void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
            {
                Bundle extras = data.Extras;
                String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
                returnDir(path);
            }
        }

        private void returnDir(String path)
        {
            Intent result = new Intent();
            result.PutExtra(CHOSEN_DIRECTORY, path);
            SetResult(Result.Ok, result);
            Finish();
        }


        public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
        {
            var files = new List<File>();
            foreach (var file in file_list)
            {
                if (onlyDirs && !file.IsDirectory)
                    continue;
                if (!showHidden && file.IsHidden)
                    continue;
                files.Add(file);
            }
            Collections.Sort(files);
            return files;
        }

        public String[] Names(List<File> files)
        {
            String[] names = new String[files.Count];
            int i = 0;
            foreach (var file in files)
            {
                names[i] = file.Name;
                i++;
            }
            return names;
        }
    }
}

Start activity as result then catch in OnActivityResult

if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
            {
                Bundle extras = data.Extras;
                String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
                // do stuff with path
            }