Hololens上的文本文件输入/输出用于写入但不能读取(Unity,Hololens,C#)

时间:2018-03-22 11:51:11

标签: c# unity3d file-io hololens

我试图在HoloLens上发现基本文件输入/输出。我使用以下代码:

public class FileInOut : MonoBehaviour {

    string plainText = "";
    TextMesh textmesh;

    // Use this for initialization
    void Start () {

        textmesh = GameObject.Find ("Text").GetComponent<TextMesh>();
        //test if Text changes normally
        textmesh.text = "Hallo";

        //create the text file and put text into it
        #if WINDOWS_UWP        

        Task task = new Task(async () =>
        {                              
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile textFileForWrite = await storageFolder.CreateFileAsync("LocalText.txt");
            await FileIO.WriteTextAsync(textFileForWrite, "Test Start");
        });
        task.Start();
        task.Wait();

        #endif
    }

    // Update is called once per frame
    void Update () {
        //Read the text file and change the text of 3D text to it (not working)
        #if WINDOWS_UWP        

        Task task = new Task(async () =>
        {                              
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile textFileforRead = await storageFolder.GetFileAsync("LocalText.txt");
            plainText = await FileIO.ReadTextAsync(textFileforRead);
            textmesh.text = plainText;
        });
        task.Start();
        task.Wait();

        #endif
    }
}

使用Start()函数编写的代码似乎可以工作,我可以通过Device Portal访问文本文件。但是我的3D Text对象的文本没有变成“Test Start”然后(尽管它在文本文件中)。

任何想法为什么写作有效但阅读没有?

1 个答案:

答案 0 :(得分:0)

两件事:

  1. 您只能从Application.persistentDataPath可靠地读/写。你应该为你的路径添加前缀:
  2. var path = Path.Combine(Application.persistentDataPath, "MyPath.txt");

    1. 如果您只是同步读取和写入字节,我建议您仅使用File操作。
    2. 写:

      File.WriteAllBytes(Encoding.UTF8.GetBytes(text));
      

      阅读:

      Encoding.UTF8.GetString(File.ReadAllBytes(path));
      

      UWP和.NET Framework支持此API,因此您也不需要条件编译指令。