如何在Xamarin Forms PCL项目上读取文本文件? [英] How to read a text file on Xamarin Forms PCL project?

查看:346
本文介绍了如何在Xamarin Forms PCL项目上读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Xamarin.Forms PCL项目上阅读一个文本文件(嵌入的资源). 在使用文件 xamarin文档中,它建议以下代码:

I need to read a text file (Embedded resource) on my Xamarin.Forms PCL project. On the working with files xamarin docs it suggests this code:

var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream)) {
    text = reader.ReadToEnd ();
}

问题是我找不到这个LoadResourceText是什么.我发现的只是它是我的Assembly中的一种类型.但是我真的不明白这意味着什么.

The problem is that I can't find what this LoadResourceText is. All I found is that it's a type in my Assembly. But I can't really understand what it means.

我在任何地方都找不到关于我需要做什么的明确实用说明.

And I can't find anywhere a clear practical explanation of what I need to do.

有帮助吗?

谢谢

推荐答案

要读取现有文件,您需要将LoadResourceText替换为PCL项目中具有的类.它用于获取包含嵌入式文件的程序集.您还需要用PCL项目的名称空间替换WorkingWithFiles.

To read an existing file you need to replace LoadResourceText with a class that you have in your PCL project. It is used to get the assembly that contains the embedded file. You will also need to replace WorkingWithFiles with the namespace of your PCL project.

您需要添加using System.Reflection;以便编译代码.

You need to add using System.Reflection; for the code to compile.

如果您想在运行时创建文件并稍后阅读,则可以使用 PCLStorage库 :

If you want to create a file at runtime and read it later you can use PCLStorage Library like this:

public async Task PCLStorageSample()
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
        CreationCollisionOption.OpenIfExists);
    IFile file = await folder.CreateFileAsync("answer.txt",
        CreationCollisionOption.ReplaceExisting);
    await file.WriteAllTextAsync("42");
}

这篇关于如何在Xamarin Forms PCL项目上读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆