Leo
Leo

Reputation: 1

Unity 3D Android and File

I have a problem with Android and Unity 3D. I have a file read code. When I put my code on the computer, it works. However, my code does not work on Android (Mobile). How can I solve this problem? Thank you.

FileInfo theSourceFile = new FileInfo(filename);
    if (System.IO.File.Exists(fname))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

EDIT updated code

string filename = "file.txt";
FileInfo theSourceFile = new FileInfo(filename);
filename = Application.persistentDataPath + "/"+filename;
System.IO.File.WriteAllText(filename,"Test");
    if (System.IO.File.Exists(filename))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

Upvotes: 0

Views: 1860

Answers (2)

Programmer
Programmer

Reputation: 125275

You must use Application.persistentDataPath on Android to be able to read anything.

Change that to string filename = Application.persistentDataPath + "/file.txt"; and your code should work fine.

Bear in mind that before the read function can work, you must write to the directory first. So file.txt must exist in Application.persistentDataPath first.

For example

string filename = Application.persistentDataPath + "/file.txt";
System.IO.File.WriteAllText(filename,"Test");

EDIT:

You new code is still not working because you had FileInfo theSourceFile = new FileInfo(filename); before filename = Application.persistentDataPath + "/"+filename;. This means that the file name is still not valid. Pay attention the order your script execute. After switching it, it worked on my Android. Below is the whole code.

string filename = "file.txt";
filename = Application.persistentDataPath + "/" + filename;
System.IO.FileInfo theSourceFile = new System.IO.FileInfo(filename);
System.IO.File.WriteAllText(filename, "Test");
if (System.IO.File.Exists(filename))
{
    System.IO.StreamReader reader = theSourceFile.OpenText();
    string text = reader.ReadLine();
    print(text);
}

Upvotes: 0

joreldraw
joreldraw

Reputation: 1736

You need to change your build settings for android Device. Change Configuration >> write access to external (sd card).

if not, your app is pointing to internal path and you need root permission in your android device.

Upvotes: 1

Related Questions