How do you write a file to android?

I’ve been cracking away day and night now at the very most simple thing that I need to do: write a file.

I just can’t get the following code to work:

string tempPath = System.IO.Path.Combine(Application.streamingAssetsPath, "rotatenumber.txt");
WWW reader = new WWW(tempPath);
while ( ! reader.isDone) {}
string filePath = Application.persistentDataPath;
System.IO.File.WriteAllBytes(filePath, reader.bytes);

Everything works fine with this until it get to the WriteAllBytes part. I’m taking a text file named rotatenumber from the streaming assets path using www and trying to write to the persistentDataPath folder…

I have also tried in Player Settings in the editor switching write permission to external (SD Card) (although my test device does not have an sd card and I don’t want the game to require one).

I want to write to the internal storage of the device. Is this even possible? How might I give the application the permission on the device to do this? I’ve read around and I thought that you are supposed to have permission to read and write to persistentDataPath…

1 Like

Okay, so after working with it for a little while I’ve now found that the culprit is ‘WriteAllBytes’.

Instead, what works for me is WriteAllText instead. I have no clue why there is the error with using WriteAllBytes, but to anyone trying this same method you can use reader.text instead of reader.bytes in conjunction with it… This works for me as the files I need to have external to the apk application are xml files.

System.IO.File.WriteAllText(filePath + "Test.txt", reader.text);

Hi @astracat111 ! I think that what you code might be missing is that you haven’t included the file name in the filePath. Have you tried doing

System.IO.File.WriteAllBytes(filePath + “/test.txt”, reader.bytes);

?

1 Like

huuuuuuuuuuuuuuuuuuuuuuuuuh…derp…

Yeah I’ll make sure to try that, thanks martejpad.

1 Like