![](/img/trans.png)
[英]How to use a Float Action Button in Xamarin.forms with a PCL project form code sharing?
[英]Xamarin.Forms (Read file from platform project in PCL code)
我正在使用PCL,iOS和Android項目構建Xamarin.Forms項目。 我的要求之一是必須從PCL讀取存儲在平台項目(iOS / Android)中的JSON文件。
我該怎么做? 我找不到這個問題的解決方案。 :(
非常感謝,尼古拉
如果要讀取的文件已嵌入平台項目程序集中,則可以使用以下代碼:
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 ();
}
確保使用項目名稱空間替換WorkingWithFiles,並使用文件名稱替換PCLTextResource.txt。
有關更多詳細信息,請參閱“ 加載作為資源嵌入的文件”中的Xamarin文檔。
另一方面,如果您想在運行時創建和讀取/寫入文件,則可以使用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");
}
我通過使用IoC容器使其工作。
在我的iOS項目中,我創建了ConfigAccess類:
public class ConfigAccess : IConfigAccess
{
public string ReadConfigAsString()
{
return System.IO.File.ReadAllText("config.json");
}
}
我還必須將以下行添加到我的AppDelegate.cs中
SimpleIoc.Default.Register<IConfigAccess, ConfigAccess>();
在我的PCL中,我只是在運行時請求ConfigAccess對象:
var configAccess = SimpleIoc.Default.GetInstance<IConfigAccess>();
var test = configAccess.ReadConfigAsString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.