I am working with Unity 2021.3.4f1. Platform target: Android 11.
Aim:
I want to create/delete/append/read data from one file stored in public folder (eg. Download) by few applications.
Problem: If I create a file in AppA then I can't read/write data on this file from AppB. I get an error:
Unauthorizedaccessexception: access to the path ... is denied.
Everything works fine if I works only on one app. It sounds like this file is signed by this app and any other app can't use this file.
I add some lines into android manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" android:required="true" />
In Debug.Log I can see that this permission (MANAGE_EXTERNAL_STORAGE) isn't allowed (i dont know why).
I tried to copy this file from Download folder into Application.temporaryCachePath but I have this same error.
Now, some lines of code:
using System;
using System.IO;
using TMPro;
using UnityEngine;
public class FileManager : MonoBehaviour
{
[SerializeField] TMP_Text fileValue;
private string fileName = "fileName.txt";
private string GlobalPath => Path.Combine(GetAndroidInternalFilesDir(), "Download", fileName);
private void Start()
{
LoadFromFile();
}
public void AddToFile(string value)
{
value += Environment.NewLine;
using (var fs = new FileStream(GlobalPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (var sw = new StreamWriter(fs))
{
sw.Write(value);
Debug.Log("AddToFile!");
}
}
LoadFromFile();
}
private void LoadFromFile()
{
if (!File.Exists(GlobalPath))
{
Debug.Log("File not exists!");
return;
}
using (var fs = new FileStream(GlobalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var sr = new StreamReader(fs))
{
fileValue.text = sr.ReadToEnd();
Debug.Log("LoadFromFile!");
}
}
}
//https://stackoverflow.com/questions/39983451/unity-android-save-files-disappears-after-updating-an-app/39994912#39994912
private static string GetAndroidInternalFilesDir()
{
string[] potentialDirectories = new string[]
{
"/mnt/sdcard",
"/sdcard",
"/storage/sdcard0",
"/storage/sdcard1"
};
if (Application.platform == RuntimePlatform.Android)
{
for (int i = 0; i < potentialDirectories.Length; i++)
{
if (Directory.Exists(potentialDirectories[i]))
{
return potentialDirectories[i];
}
}
}
Debug.LogError("Path not exists!");
return "";
}
}
I know Android 11 has made things difficult for memory file management. However, maybe there are any ideas how I could deal with this problem?
Or possibly some other method of transferring information between several applications on one device. Without internet access?