如何读取文件 (Metro/WinRT)文件、Metro、WinRT

2023-09-06 06:23:45 作者:别挡道i

我对这个看似简单的任务的明显复杂性感到非常震惊.我知道我必须使用 StorageFile 类,并且我发现了这个 示例,但我只想读取一个我知道路径的文件,并将其数据作为文本读取到字符串中.

I'm quite astounded by the apparent complexity of this seemingly simple task. I know that I have to use the StorageFile class, and I've found this example, but I just want to read one single file, to which I know the path, and read it's data as text into a string.

从我收集到的资料来看,要使用 StorageFile 读取文件,我必须通过一堆接口;IAsyncOperationIAsyncOperationCompletedHandler.

From what I've been able to gather, to read a file with StorageFile, I have to go through a bunch of interfaces; IAsyncOperation<StorageFile> and IAsyncOperationCompletedHandler.

一定有更好(更简单)的方法.比如:

There must be a better (simpler) way. Something like:

using (StorageFile sf = StorageFile.OpenAsync("myFile.txt"))
{
    string line = sf.ReadLine();
}

显然这不起作用,但也许我错过了什么,或者有人可以向我解释如何以不同的方式读取文件?

Obviously this doesn't work, but maybe I've missed something, or someone could explain to me how to read a file in a different way?

推荐答案

此网页可能会有所帮助:http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html

This web page might be helpful: http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html

相关代码:

public string CurrentFileBuffer
{
    get; private set;
}

public async void ReadTextFile(string Path)
{
    var folder = Package.Current.InstalledLocation;
    var file = await folder.GetFileAsync(Path);
    var read = await FileIO.ReadTextAsync(file);
    CurrentFileBuffer = read;
}