如何阅读文件(Metro/WinRT)

ann*_*sly 15 c# wpf microsoft-metro windows-8 windows-runtime

我对这个看似简单的任务的明显复杂性感到震惊.我知道我必须使用这个StorageFile类,我已经找到了这个例子,但我只是想读一个单独的文件,我知道路径,并将它的数据作为文本读入字符串.

从我能够收集的内容,到阅读文件StorageFile,我必须经历一堆接口; IAsyncOperation<StorageFile>IAsyncOperationCompletedHandler.

必须有更好(更简单)的方式.就像是:

using (StorageFile sf = StorageFile.OpenAsync("myFile.txt"))
{
    string line = sf.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*son 30

此网页可能会有所帮助: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;
}
Run Code Online (Sandbox Code Playgroud)

  • 真是一个很棒的链接!;) (5认同)

Dan*_*ron 5

Windows.Storage.FileIO有一堆辅助/实用程序方法,它们只需一行代码即可完成工作,而不是使用StorageIO接口和类.

例如

ReadLineAsync()
ReadTextAsync()
WriteLineAsync()
WriteTextAsync()
Run Code Online (Sandbox Code Playgroud)