如何从异步操作返回字符串?

时间:2013-07-23 07:34:37

标签: c# file-io asynchronous

我正在使用PCLStorage,需要一种方法来读取文件。我将使用JSON进行序列化,所以我只需要从文件中读取保存的内容:

        public async string ReadFromFile(string filename)
        {
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
            IFile file = await folder.GetFileAsync(filename);
            string content = await file.ReadAllTextAsync();

            return content;
        }

但是我不能返回字符串,它必须是无效的,任务或任务。

我可以通过这种方法返回字符串吗?也许通过调用另一种方法?

1 个答案:

答案 0 :(得分:2)

您需要返回Task<string>,如下所示:

public async Task<string> ReadFromFile(string filename)
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", 
        CreationCollisionOption.OpenIfExists);
    IFile file = await folder.GetFileAsync(filename);
    string content = await file.ReadAllTextAsync();

    return content;
}