如何读取文件(Metro / WinRT)

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

从我能够收集到的,用StorageFile读取文件,我必须经历一堆接口; IAsyncOperationIAsyncOperationCompletedHandler

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

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

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

此网页可能会有所帮助: 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; } 

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

例如

 ReadLineAsync() ReadTextAsync() WriteLineAsync() WriteTextAsync() 

您可以使用以下命令获取文件:

 StorageFile file3 = await StorageFile.GetFileFromPathAsync(@"C:\myFile.txt"); 

您可以像这样使用FileIO类。

 public async void Read(IStorageFile file) { var lines = await FileIO.ReadLinesAsync(file); }