C# 如何读取文件 (Metro/WinRT)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12703816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read file (Metro/WinRT)
提问by annonymously
I'm quite astounded by the apparent complexity of this seemingly simple task. I know that I have to use the StorageFileclass, 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类,我找到了这个例子,但我只想读取一个我知道路径的文件,并将它的数据作为文本读入一个字符串。
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.
从我能够收集到的内容来看,要使用 读取文件StorageFile,我必须通过一堆接口;IAsyncOperation<StorageFile>和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?
显然这不起作用,但也许我错过了一些东西,或者有人可以向我解释如何以不同的方式读取文件?
采纳答案by Matthew Watson
This web page might be helpful: http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html
此网页可能会有所帮助:http: //blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html
Relevant code:
相关代码:
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;
}
回答by Dangling Neuron
Windows.Storage.FileIOhas a bunch of helper/utility methods that do the job in a single line of code rather than using StorageIO interfaces and classes.
Windows.Storage.FileIO有一堆帮助器/实用程序方法,它们在一行代码中完成工作,而不是使用 StorageIO 接口和类。
e.g.
例如
ReadLineAsync()
ReadTextAsync()
WriteLineAsync()
WriteTextAsync()
回答by vidstige
You can use the FileIOclass like so.
你可以FileIO像这样使用这个类。
public async void Read(IStorageFile file)
{
var lines = await FileIO.ReadLinesAsync(file);
}
回答by user2999722
You can get your file by using this:
您可以使用以下方法获取文件:
StorageFile file3 = await StorageFile.GetFileFromPathAsync(@"C:\myFile.txt");

