I have anayltics in my Unity3D game and I realised that some Android devices throw the UnauthorizedAccessException when I am trying to create a folder on the device.
Have a look at the code that throws the exception:
static void SaveToCache(Entry entry, byte[] bytes) {
if (entry.file != null) {
string path = Path.GetDirectoryName(entry.file);
try {
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
File.WriteAllBytes(entry.file, bytes);
} catch (Exception ex) {
Analytics.LogException(ex, "couldn't save to cache: " + path);
}
}
}
The code looks good for me, but perhaps I’m missing something… It does not throw on my test devices - I only have the stack trace from my analytics.
More relevant code is how I build the path:
static readonly char DirectorySeparator = Path.DirectorySeparatorChar;
static string BundleFile(string id, string languageCode) {
StringBuilder sb = new StringBuilder();
sb.Append(BundlePath());
sb.Append(id);
sb.Append("_");
sb.Append(languageCode.ToLower());
sb.Append(".json");
return sb.ToString();
}
static string BundlePath() {
StringBuilder sb = new StringBuilder();
sb.Append(Application.persistentDataPath);
sb.Append(DirectorySeparator);
sb.Append("bundles");
sb.Append(DirectorySeparator);
return sb.ToString();
}
Please tell me if someone out there has similar issues. Can’t I rely on Application.persistentDataPath
? Is there a better way to build the path for the cache files?
Edit: Found the problem. Application.persistentDataPath
returns an empty string in rare cases/some devices. Anyone has this seen before?
Edit: for the solution see persitent data path handling in Unity with fallback · GitHub