I have an application that I want to build in android. I provide a path of a folder and using the Directory.GetFiles() I acquire the list of files of a specific type. I load two types of files .jpg and .txt .
The whole process runs without any problem in Unity Editor. When I build in android I can’t get the list of paths for txt files from the selected folder. The process works for .jpg files but not for .txt files. I use the same functions to get the file paths from the selected folders. I cannot read the txt file even when I use hard-coded file path.
Function to load file paths of a selected type from a given path:
string[] LoadFiles(string path, string type)
{
string[] filePaths = Directory.GetFiles(path, $"*.{type}", SearchOption.TopDirectoryOnly);
return filePaths;
}
Execution of LoadFiles to get file paths for jpg and txt files:
jpgPaths = LoadFiles(ImagesPath, "jpg");
txtPaths = LoadFiles(TxtPath, "txt");
I get the file paths for .jpg files, but I can’t get the paths for .txt files (the list is empty after the execution of the function).
Also I have tried to read a .txt file using hardcoded path with the following:
classesNames = File.ReadAllLines(path);
Where path is the following: “/storage/emulated/0/txt_folder/labels.txt”
In android logcat I get an error for file permissions:
Error Unity UnauthorizedAccessException: Access to the path “/storage/emulated/0/txt_folder/labels.txt” is denied.
I have cross-checked to load an image using hardcoded path, and It worked fine without any error regarding permissions.
I have the following function to run at Start():
void RequestPermissions()
{
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) &&
Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
return;
}
Permission.RequestUserPermission(Permission.ExternalStorageRead);
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
}
When I run the app, a window pops up to allow access to folders.
Also I have added permissions to AndroidManifest.xml:
I can’t understand how I can read jpg files and not txt files.