简体   繁体   English

如何在Xamarin Forms PCL项目上阅读文本文件?

[英]How to read a text file on Xamarin Forms PCL project?

I need to read a text file (Embedded resource) on my Xamarin.Forms PCL project. 我需要在我的Xamarin.Forms PCL项目上读取文本文件(嵌入式资源)。 On the working with files xamarin docs it suggests this code: 使用文件 xamarin文档时,它建议使用以下代码:

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 ();
}

The problem is that I can't find what this LoadResourceText is. 问题是我找不到这个LoadResourceText是什么。 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. 而且我找不到任何关于我需要做什么的明确实际解释。

Any help? 有帮助吗?

Thanks 谢谢

To read an existing file you need to replace LoadResourceText with a class that you have in your PCL project. 要读取现有文件,您需要将LoadResourceText替换为PCL项目中的类。 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. 您还需要将WorkingWithFiles替换为PCL项目的命名空间。

You need to add using System.Reflection; 您需要using System.Reflection;添加using System.Reflection; for the code to compile. 用于编译的代码。

If you want to create a file at runtime and read it later you can use PCLStorage Library like this: 如果要在运行时创建文件并稍后阅读,可以使用PCLStorage Library,如下所示:

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM