Unity for iOS中的文本文件读/写

时间:2018-04-28 11:26:23

标签: objective-c xcode unity3d unityscript

我正在尝试在Unity for iOs项目中获取文本文件读/写访问权限。 我做的是

        //Read
        StreamReader reader = new StreamReader(Application.persistentDataPath + "/record.txt"); 
        string record = reader.ReadToEnd ();
        string[] records = record.Split(new string[] { " " }, StringSplitOptions.None);
        firstname = records [0]; lastname = records [1]; loginName = records [2]; password = records [3];
        reader.Close();
        email.transform.GetComponent<InputField> ().text = loginName;
        pwd.transform.GetComponent<InputField> ().text = password;


        //Write

        File.WriteAllText(Application.persistentDataPath + "/record.txt", String.Empty);
        //File.Create (Application.persistentDataPath + "/record.txt").Close ();
        StreamWriter writer = new StreamWriter (Application.persistentDataPath + "/record.txt", true);
        writer.WriteLine (Login.firstname + " " + Login.lastname + " " + Login.loginName + " " + Login.password);
        writer.Close ();

然后我将文件包含在Build Phases中 - &gt;复制捆绑资源,因此该文件位于项目内。 但是当我在设备中运行应用程序时,我无法读取文件并获得消息

IsolatedStorageException: Could not find file "/var/mobile/Containers/Data/Application/D48E51C7-F2EE-48CF-9B84-6602CE135EBC/Documents/record.txt".
  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0 
  at System.IO.File.OpenRead (System.String path) [0x00000] in <filename unknown>:0 

可能出现什么问题?

1 个答案:

答案 0 :(得分:0)

将文本文件放在Resources文件夹中并不是一个好习惯,因为Unity总是会尝试序列化您在构建时放在该文件夹中的所有内容。而是将您的文件复制到StreamingAssets文件夹,然后使用

StreamReader sr = new StreamReader(Path.Combine(Application.streamingAssetsPath,"text.txt"));

这样可以正常工作。注意:对于您不希望Unity在构建时触摸的文件,请将它们放在StreamingAssets中。