Android/iOS 中的 Xamarin 通用 Xamarin.Forms 代码

Xamarin common Xamarin.Forms code across Android/iOS

我希望在 Visual Studio 2015 中创建一个 Xamarin Forms PCL,它表示 Xamarin Android 项目和 Xamarin iOS 项目的通用应用程序代码(但是不是其他任何东西,即:Windows 或 Windows phone)。我目前正在使用 PCL 配置文件 111,这是由提供的 Xamarin 模板创建的。

一切都很好,直到我遇到对 System.IO.FileStream 的支持。基于这篇文章(在保存和加载文件部分): https://developer.xamarin.com/guides/xamarin-forms/working-with/files/

Android 和 iOS 都可以立即使用 System.IO 的大部分功能,这在我的 Android 和 iOS 项目中很明显我可以在其中使用与 read/write 文件相同的 FileStream。

由于代码是相同的,将它维护在一个地方会更有意义,但我似乎无法找到可以执行此操作的配置文件(或 visual studio 模板) ,有什么想法吗?

我还浏览了这里: http://blog.stephencleary.com/2012/05/framework-profiles-in-net.html

但是 Portable Class 库配置文件 table 没有提到 Xamarin/Android/iOS.

难道没有比 111 更窄的 PCL 配置文件可以提供我想要的吗?我唯一的选择是使用 DependencyService 设置吗?也许共享代码项目会更干净?

编辑:虽然我提到 FileStream 作为我正在尝试做的事情的例子,但我想解决维护任何通用代码的问题 Android/iOS(并且只有那些平台,而不是 Windows/Windows Phone/Silverlight/ASP.NET 等)对于 Android 和 iOS 支持使用通用代码的功能的任何情况,但其他平台之一没有。

跨平台IO可以使用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");
}

尝试在 Xamarin Studio 中编辑设置。在 Xamarin Studio 中,不同的 Xamarin 目标被列为 PCL 的目标选项。对于配置文件 111,您将看到 Xamarin 平台成为目标。在这种情况下,共享项目可能是您的最佳选择。

我认为你应该尝试 File System Plugin(Xamarin 组件)

The File System Plugin for Xamarin and Windows provides a consistent, portable set of local file IO APIs for .NET, Windows Phone, Windows Store, Xamarin.iOS, Xamarin.Android, and Silverlight. This makes it easier to create cross-platform .NET libraries and apps.

这是一个示例

public async Task CreateRealFileAsync()
 { // get hold of the file system IFolder
 rootFolder = FileSystem.Current.LocalStorage; // create a folder, if one does not exist already
 IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists); // create a file, overwriting any existing file
 IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting); // populate the file with some text 
await file.WriteAllTextAsync("Sample Text...");
 }

Thia 会让你在一个通用的PCL项目中编写所有文件操作

Is there simply not a PCL profile any narrower than 111 which can provide what I want? Is my only option to use a DependencyService setup? Maybe a Shared Code project would be cleaner?

配置文件 111 是您将要获得的"closest"。

就个人而言,对于这种情况,您只需要 Xamarin.Android 和 Xamarin.iOS` 支持您的解决方案,使用 Shared Project 是最快和最干净的方式。共享 PCL 库很棒,但是,如果您不需要所有跨平台支持(因此也不需要限制),请使用共享文件...

稍后,如果需要,您可以随时将该代码迁移到基于 PCL 的库 and/or 依赖于平台的库。