繁体   English   中英

在 Hololens 2 上处理文件(UWP 到 .NET)

[英]Working with Files on Hololens 2 (UWP to .NET)

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

我想读取文本文件(.txt) 以及二进制文件(.raw)。 在使用 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()System.IO上不起作用,我想文件 stream 和二进制阅读器也不能正常工作。

So my Questions is how can i load the data when using the Hololens through the specific UWP API and then use the System.IO API for the rest?

选择文件的示例(为以后的读者获取路径):

#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

编辑:

为了更清楚,我还有另一个 class 它使用文件路径(来自选择器)并在 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方法的代码一起使用吗?

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

#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

With this code i can get a stream from an Windows StorageFile and generate a StreamReader or a BinaryReader through which i can use the rest of my calculations written with System.IO .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM