15

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

从我收集到的信息来看,要使用 读取文件StorageFile,我必须通过一堆接口;IAsyncOperation<StorageFile>IAsyncOperationCompletedHandler

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

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

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

4

4 回答 4

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;
}
于 2012-10-03T07:59:46.713 回答
5

Windows.Storage.FileIO有一堆帮助/实用程序方法,它们在一行代码中完成这项工作,而不是使用 StorageIO 接口和类。

例如

ReadLineAsync()
ReadTextAsync()
WriteLineAsync()
WriteTextAsync()
于 2012-10-03T11:16:04.070 回答
4

您可以使用以下方法获取文件:

StorageFile file3 = await StorageFile.GetFileFromPathAsync(@"C:\myFile.txt");
于 2013-12-02T06:09:13.200 回答
0

你可以FileIO像这样使用这个类。

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

}
于 2013-08-28T19:31:04.293 回答