Hololens 2 -无法访问ApplicationData.Current.RoamingFolder中的文件.&l



我是Hololens 2编程新手。我正在开发一个使用Unity for Holo2的UWP应用程序,该应用程序使用XML配置文件来接收有关3D对象在与标记相对位置的放置的信息。当我尝试从资源文件夹(Unity和Hololens)和PC AppData (Unity)读取和处理文件时,它工作得很好,但当我尝试从Hololens AppData文件夹读取文件时,我遇到了一些问题(也当我尝试从特殊文件夹KnownFolders读取文件时)。我使用了"ApplicationData.Current.RoamingFolder"。Path'作为内部UWP文件夹(可从DevicePortal访问),而StorageFolder &在新任务中获取async方法的StorageFile。我也修改了package的代码。appxmanifest与正确的FileTypeAssociation .xml我希望在ApplicationData.Current.RoamingFolder.Path路径中使用的Microsoft帐户电子邮件(user@mail.com)不是异步方法的问题。

//...
using System.Xml.Linq;
using System.Threading.Tasks;
//...
#if WINDOWS_UWP
using Windows.Storage;
#endif

的加载
#if WINDOWS_UWP      
try
{
folderPathName = ApplicationData.Current.RoamingFolder.Path;
using (Stream s = openFileUWP(folderPathName, filenameWithExtension)) 
{
document = XDocument.Load(s);
}
}
catch (Exception e)
{
document = XDocument.Parse(targetFile.text); //the XML file in Resources folder
}
#else
//...
#endif

这里openFileUWP函数

#if WINDOWS_UWP
private Stream openFileUWP(string folderName, string fileName)
{
Stream stream = null;
Task task = new Task(
async () =>
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(folderName);
StorageFile file = await folder.GetFileAsync(fileName);  
stream = await file.OpenStreamForReadAsync(); 
});

task.Start();
task.Wait();            
return stream;
}
#endif

您正在使用Task构造函数,建议不要这样做。参见任务构造函数。

同样,Task构造函数接受一个Action。因此,没有任务等待,当任务启动时,它几乎立即完成。

同样,阻塞可能阻塞,甚至死锁你的UI。

试试这个:

private async Task<Stream> openFileUWP(string folderName, string filename)
{
var folder = await StorageFolder.GetFolderFromPathAsync(folderName);
var file = await folder.GetFileAsync(filename);  
var stream = await file.OpenStreamForReadAsync(); 
return stream;
}

对于在UWP平台上读取文件,可以参考创建、写入和读取文件- UWP应用程序| Microsoft Learn和以下代码。

#if ENABLE_WINMD_SUPPORT
using Windows.Storage;
using Windows.Storage.Streams;
#endif
#if ENABLE_WINMD_SUPPORT
private async void ReadFile()
{
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read); 
//You can return the stream here. Note that the type of this stream is Windows.Storage.Streams.IRandomAccessStream.
ulong size = stream.Size;
using (var inputStream = stream.GetInputStreamAt(0))
{
using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
{
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
string text = dataReader.ReadString(numBytesLoaded);
}
}
}
#endif

最新更新