i´m trying to add files from a directory to spinner list, but i got nothing, (spinner list is empty) hoyever the folder countains 3 files in it.
i checked whether the folder exists or not, (the folder exists)
then i tried to show a message telling if any file found in the folder (i got no message)
this is what i tried so far :
public class MainActivity : Activity
{
Button btnGetFiles;
Spinner spinnerGetFiles;
List<string> fileList;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
spinnerGetFiles = FindViewById<Spinner>(Resource.Id.spinnerGetFiles);
btnGetFiles = FindViewById<Button>(Resource.Id.btnGetFiles);
btnGetFiles.Click += delegate
{
fileList = GetFilesFromDirectory("/storage/emulated/0/MyFolder");
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, fileList);
spinnerGetFiles.Adapter = adapter;
};
}
List<string> GetFilesFromDirectory(string strDirectoryPath)
{
List<string> files = new List<string>();
if (Directory.Exists(strDirectoryPath))
{
Toast.MakeText(Application.Context, "Directory found", ToastLength.Long).Show();
string[] fileList2 = Directory.GetFiles(strDirectoryPath);
foreach (string file in fileList2)
{
files.Add(Path.GetFileName(file));
Toast.MakeText(Application.Context, "File found : " + file, ToastLength.Long).Show();
}
}
else { Toast.MakeText(Application.Context, "No directory was found!!", ToastLength.Long).Show(); }
return files;
}
}
From the storage you accessed(
/storage/emulated/0/),we could find that you want to access theexternal storage.To access the external storage, we need to add the external storage permissions as follows:
And we also need to add runtime permission after Android 6.0 (API level 23).
And there is an official sample here about how to access
external storage, you can check it here: local files.For more information, you can check: External storage.
And as a test, I added a Button to the sample code to get the generated file
count.txtlocal files using the following code, and it could list the file correctly: