【发布时间】:2022-08-03 16:05:52
【问题描述】:
我正在使用 Unity 为 HoloLens 2 开发应用程序。我仍然很困惑如何连接 UWP 环境和 .NET API。
我想读文本文件(.txt) 以及二进制文件(。生的)。在使用 Hololens(UWP 环境)时,我使用 Windows.Storage 和 FileOpenPicker()。我目前已经对文件的处理进行了编码,以便我可以在 Unity 编辑器(.NET 环境)中测试它们。因此我使用File.ReadAllLines(filePath) 来获取txt 文件并将每一行作为字符串,对于二进制文件我使用FileStream fs = new FileStream(filePath, FileMode.Open) 和BinaryReader reader = new BinaryReader(fs)。来自System.IO 的方法File.ReadAllLines() 不适用于Hololens,我想文件流和二进制阅读器也不能正常工作。
所以我的问题是如何在通过特定的 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.Storage.StorageFile 并对其进行更改以使其与使用System.IO 方法的代码一起使用吗?
-
在上面的统一项目中使用 File.ReadAllLines System.IO api 时会抛出任何异常吗?
-
@NicoZhu-MSFT 是的。我使用 Filepicker 加载并获取 Hololens 设备上的路径,我在 File.ReadAllLines(pathOnHololens) 中使用它并得到错误 DirectoryNotFoundException:找不到路径的一部分。我检查了类似于
C:\\Data\\Users\\userEmail\\Documents\\Datasets...的路径,其中 userEmail 是当前 Hololens 用户的 MS 帐户。 -
UWP 在沙箱中运行,为什么不使用 windows storage api 读取文件?请参考这个link
-
@NicoZhu-MSFT 感谢您的帮助和链接。如果我正确阅读了所有内容,则 Windows 存储 API 不适用于 Unity 编辑器。所以我必须加载两次,一次用于 Hololens 2 和 Windows/Unity?此外,这意味着对于二进制文件,我需要使用 Windows 存储缓冲区 (IBuffer) 而不是 FileStream 和 BinaryReader?
-
如果您想在 Unity 中使用 WinRT API,您可能需要使用 Unity 条件编译功能并参考docs.microsoft.com/en-us/windows/mixed-reality/develop/unity/… 添加 WinRT 用法。如果需要,我们可以提供一些使用 FolderPicker 和 StreamWriter 的示例代码 sn-ps。常见的解决方案是创建一个 Visual Studio 项目,然后将代码迁移到 Unity 并确保在经过全面测试后将它们包装在 ENABLE_WINMD_SUPPORT 部分中。
标签: c# unity3d uwp hololens il2cpp