在Hololens 2上使用文件(UWP到.NET)



我正在用Unity为HoloLens 2开发一个应用程序。我仍然很困惑如何连接UWP环境和.NET API。

我想阅读文本文件(.txt(以及二进制文件

因此,我的问题是,当通过特定的UWP API使用Hololens时,如何加载数据,然后使用System.IO API处理其余数据

拾取文件的示例(为以后的读取器获取路径(:

#if !UNITY_EDITOR && UNITY_WSA_10_0

UnityEngine.WSA.Application.InvokeOnUIThread(async () =>
{
var filepicker = new FileOpenPicker();
filepicker.FileTypeFilter.Add("*");

var file = await filepicker.PickSingleFileAsync();

UnityEngine.WSA.Application.InvokeOnAppThread(() =>
{
path = (file != null) ? file.Path : "Nothing selected";
name = (file != null) ? file.Name : "Nothing selected";
Debug.Log("Hololens 2 Picker Path = " + path);

}, false);     
}, false);
#endif
#if UNITY_EDITOR
OpenFileDialog openFileDialog1 = new OpenFileDialog();
path = openFileDialog1.FileName;
...
#endif

编辑:

为了更清楚地表明这一点,我有另一个类,它使用文件路径(来自选择器(,并在System.IO方法的帮助下,根据扩展名(.txt、.raw(将文件读取为文本文件或二进制文件。

// For text file
string[] lines = File.ReadAllLines(filePath);
string rawFilePath = "";

foreach (string line in lines)
{
}
// For binary file
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader reader = new BinaryReader(fs);

但在Hololens 2上,File.ReadAllLines(filePath)抛出DirectoryNotFoundException: Could not find a part of the path异常。我可以使用Windows.Storage0并更改它,使其与使用System.IO方法的代码一起工作吗?

我想我找到了一个答案,我希望它能帮助其他人解决同样的问题:

#if !UNITY_EDITOR && UNITY_WSA_10_0
public async Task<StreamReader> getStreamReader(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var randomAccessStream = await file.OpenReadAsync();
Stream stream = randomAccessStream.AsStreamForRead();
StreamReader str = new StreamReader(stream);
return str;
}
#endif

有了这段代码,我可以从WindowsStorageFile获得一个流,并生成一个StreamReaderBinaryReader,通过它我可以使用用System.IO编写的其余计算。

最新更新