- Home /
How do I Read/Save File in Android
I'm developing an App for Android and I need to Read and save files in .txt. I'm using C# and the library System.IO to read and write my .txt files. When I Start my App I need to Read some .txt files that are locate in a folder. So to give the Path to this folder I'm using:
string path = Application.PersistentDataPath + "/file.txt"; StreamReader file = new StreamReader(path);
But when i Build the project and put in my cellphone, the android can't find my .txt files. I tried to put a text object to see where the variable path is, the return that i get is:
/storage/sdcard0/Android/data/com.andrew.myApp/files/teste.txt
I've tried to change in playerprefs the write acess and install location. tried every combination and the App couldn't find my .txt file.
If anyone can help it would be great
What do you mean by "doesn't find"? What exception do you get? Can you write files?
As an aside, use Path.Combine(Application.PersistentDataPath, "file.txt")
- It's neater and works better across different platforms.
Answer by BytesCrafter · Aug 04, 2016 at 03:09 PM
Hope this help, I am also working on a project that needs a method something like this. :D
public class TestScript : MonoBehaviour { public void SaveEncodedFile() { string path = Application.persistentDataPath;
File.WriteAllText(path + "/Testest.txt", testst.text);
}
public void LoadEncodedFile()
{
string path = Application.persistentDataPath;
tests.text = File.ReadAllText(path + "/" + "TempName" + ".txt");
}
}
Answer by ArshakKroyan · Dec 17, 2015 at 02:42 PM
Hi @and_duch. Are you sure that you have selected "PlayerSettings->OtherSettings->WriteAccess to External(SDCard)?
Also try Application.dataPath instead of Application.persistentDataPath. I don't remember which one is OK for Android.
Have you got any error which will be helpful ?
Answer by OgnjenSelver · Feb 11 at 09:28 AM
One way is to use: 1. public TextAsset YourFile; 2.Drag it in inspector Printing it on UI would look something like: (i have in my script "public Text txt;" drag and drop your UI element and also include using UnityEngine.UI;) txt.text=YourFile.text;