在共享库 Xamarin c# 中读取文件 [英] Read file in Shared Library Xamarin c#
问题描述
我在共享库中保存了一些 .json 文件.
I have saved some .json files in the shared library.
我已经设法通过代码在 iOS 中正常阅读
I have managed to read just fine in iOS by the code
string fileName = $"Files/file_name.json";
var path = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var streaReader = new StreamReader(stream))
{
return streaReader.ReadToEnd();
}
然而,我一直在努力为 Android 做同样的事情.我无法读取资产,因为它位于共享库中.
However, I have been struggling to do the same for Android. I can't read from assets since it is in the Shared Library.
using (var stream = Application.Context.Assets.Open("Files/file_name.json))
如果我在资源文件夹下的 Android 项目中拥有该文件,则使用上面的实时文件确实有效.
Using this live above does work if I had the file in the Android project under the assets folder.
我想保留一份用于两个平台的文件副本.
I want to keep one copy of the file used for both platforms.
推荐答案
将您的共享"文件添加到您的解决方案(在您的 PCL/NetStd/Shared 项目中的文件夹中即可,只需将构建类型设置为
None
).
在您的 Android 项目中,创建一个链接到 Assets
中的文件,构建类型为 AndroidAsset
.>
BundleResource
的文件.In your Android project, create a link to the file in the Assets
with a build type of AndroidAsset
.
Android 示例:
<ItemGroup>
<AndroidAsset Include="..\Forms_30\her.png">
<Link>Assets\her.png</Link>
</AndroidAsset>
</ItemGroup>
iOS 示例:
<ItemGroup>
<BundleResource Include="..\Forms_30\her.png">
<Link>her.png</Link>
</BundleResource>
</ItemGroup>
注意:您可以手动编辑 .csproj
或使用 PCL/NetStd 库中文件的起始位置从 Finder/Explorer 执行拖放操作,但要选择创建删除文件时的链接.
Note: You can manually edit the .csproj
or perform a drop/drop from Finder/Explorer using the starting location of the file in your PCL/NetStd library but make you select create a link when you drop the file.
现在,您可以通过 DI 使用自己的平台相关代码,也可以使用 Xamarin.Essentials
从您的 PCL/NetStd 库访问这些只读应用程序捆绑文件.
Now you can either use your own platform-dependent code via DI or use Xamarin.Essentials
to access these read-only app bundled files from your PCL/NetStd library.
using (var stream = await FileSystem.OpenAppPackageFileAsync("her.png"))
{
~~~
}
这篇关于在共享库 Xamarin c# 中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!