HoloLens2读取眼镜中的本地文件

工程目标

    在HoloLens2中实现读取眼镜中的本地文件,由于HoloLens中没有磁盘的概念,所以在本工程中使用的方法是KnownFolder,通过该方法访问位于眼镜Picture、Video、Music及Document文件夹下的文件。

实现方法

存放文件

本工程中使用的是KnownFolders.PicturesLibrary方法,将需要读取的文件放入HoloLens中的Picture文件夹下:
在这里插入图片描述

文件内容为123ReadSuccess
在这里插入图片描述

编写脚本

该脚本实现了将读取到的文件数据显示在场景中的功能,其中变量AsyncContentTest显示的是数据传回主进程调用,ReadContentTest显示的是在异步线程中的调用。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System.Text;
#if WINDOWS_UWP//UWP下编译
using Windows.Storage;
using System.Threading.Tasks;
using System;
using System.Threading;
#endif


public class UWP_KnownFolders : MonoBehaviour
{
    public Text ReadContentTest;
    public Text AsyncContentTest;
    bool isReadBegin = false;
    string list = "AsyncFail";
    string fileName = "ReadTest.txt";
    // Start is called before the first frame update
    void Start()
    {

    }
    public void ReadBegin()
    {
        ReadContentTest.text = "Fail";
        list = OpenFileForRead(fileName);
        AsyncContentTest.text = list;
        
    }
    private Stream OpenFileForRead(string fileName)
    {
        string stlName = "Wait";
        Stream fileStreamAsync = null;
#if WINDOWS_UWP
        Task task = new Task(
        async () => {
            //读取文件内容
            StorageFolder modelFolder = KnownFolders.PicturesLibrary;
            IStorageItem fileExist = await modelFolder.TryGetItemAsync(fileName);
            if(fileExist != null){
                StorageFile modelFile = await modelFolder.GetFileAsync(fileName);
                fileStreamAsync = await modelFile.OpenStreamForReadAsync();
                //文本内容显示
                byte[] data = new byte[fileStreamAsync.Length];
                fileStreamAsync.Read(data, 0, 80);
                stlName = Encoding.UTF8.GetString(data); 
            }
            else
                stlName = "none";
        });
        task.Start();
#endif
        while (stlName == "Wait")
        {
        }
        return fileStreamAsync;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

创建场景

①在场景中创建两个UI->text
②将UWP_KnownFolders脚本挂在GameObject下,选择text
在这里插入图片描述

显示

将场景生成UWP应用后,将应用部署到眼镜中,点击触发Read Begin()函数的按钮,文本中的内容显示在场景中。

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值