简体   繁体   English

Xamarin.Forms(以PCL代码从平台项目中读取文件)

[英]Xamarin.Forms (Read file from platform project in PCL code)

I am building a Xamarin.Forms project with a PCL, iOS and Android project. 我正在使用PCL,iOS和Android项目构建Xamarin.Forms项目。 One of my requirements is that I have to read a JSON file stored in the platform project (iOS/Android) from the PCL. 我的要求之一是必须从PCL读取存储在平​​台项目(iOS / Android)中的JSON文件。

How can I do this please? 我该怎么做? I can't find a solution for this problem. 我找不到这个问题的解决方案。 :( :(

Thank you very much, Nikolai 非常感谢,尼古拉

If the file that you want to read is embedded in the platform project assembly you can use the following code: 如果要读取的文件已嵌入平台项目程序集中,则可以使用以下代码:

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

Make sure that you replace WorkingWithFiles with namespace of your project and PCLTextResource.txt with name of the file. 确保使用项目名称空间替换WorkingWithFiles,并使用文件名称替换PCLTextResource.txt。

Check Xamarin documentation at Loading Files Embedded as Resources for more details 有关更多详细信息,请参阅“ 加载作为资源嵌入的文件”中的Xamarin文档。

If on the other hand you want to create and read/write files at runtime you can use PCLStorage library: 另一方面,如果您想在运行时创建和读取/写入文件,则可以使用PCLStorage库:

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

I got it working by using an IoC container. 我通过使用IoC容器使其工作。

In my iOS project I have created a ConfigAccess class: 在我的iOS项目中,我创建了ConfigAccess类:

public class ConfigAccess : IConfigAccess
{
    public string ReadConfigAsString()
    {
        return System.IO.File.ReadAllText("config.json");
    }
}

I also had to add the following line to my AppDelegate.cs 我还必须将以下行添加到我的AppDelegate.cs中

SimpleIoc.Default.Register<IConfigAccess, ConfigAccess>();

And in my PCL I am simply asking for a ConfigAccess object during runtime: 在我的PCL中,我只是在运行时请求ConfigAccess对象:

var configAccess = SimpleIoc.Default.GetInstance<IConfigAccess>();
var test = configAccess.ReadConfigAsString();

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

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