Problems with Directory.GetFiles() on Android

I started to develop an Android app, in which I would like to implement an Import/Export system where you can import and export the data in txt files.

To create the import part, I made a file browser, which displays the content of the currently opened directory (sub-directories and txt files), just like this:

string[ ] subdirectories = Directory.GetDirectories(currentpath, “*”, SearchOption.TopDirectoryOnly);
string[ ] txtfiles = Directory.GetFiles(currentpath, “*.txt”, SearchOption.TopDirectoryOnly);
//display them

The GetDirectories part works fine, it’s the GetFiles() that behaves oddly.
The problem is, that the Directory.GetFiles() doesn’t return the txt files unless they were created by the app (with the export function), which is quite unpractical.

I appreciate any feedback.

UPDATE: I tried running my program on a Xiaomi, a Samsung and a Huawei phone (I had given the file access permission on all of them beforehand) and the problem only occurs on the Xiaomi one, so it probably has something to do with MIUI.

Filesystems are always tricky on mobile devices because of the security layers built into the OS.

When you have issues it may be useful to study the log for any signs of exceptions related to permissions or entitlements or directory accesses in general.

Good luck!

1 Like

Hi Obambe_69420,

I have the same problem. The apk running in Android 9 works fine (Asus Rog 2). If I test in Android 12 (Redmi Note 9 Pro or Samsung Galaxy Tab Active 3) I just can see the files created by the app.

Did you find the solution??

I believe newer Android version have tightened the security. You may need to use android file chooser to get access to those files.

Because you’re trying to access SD Card and doesn’t request permission before.
I’m simply fixed it by go to:
Edit>Project Settings>Player>Other Settings>Configuration - Write Permission => Change it to External (SDCard).

2 Likes

UnityEngine.Android.Permission.RequestUserPermission(Permission.ExternalStorageRead);