AssetManager与内部存储:如何将跨平台的config.json文件存储在我稍后要编辑的Xamarin Android中?

时间:2019-03-22 23:12:57

标签: xamarin.android android-assets android-internal-storage android-assetmanager

我希望能够预先配置我的Android应用程序以包含一个可读写的json文件,该文件也可以在其他平台(iOS,UWP)上使用。我开始查看AssetManager,但发现只能读取文件,以后不能编辑。

内部存储是答案吗?如果是这样,我如何用此文件预填充应用程序的内部存储?除了在C#代码中执行完全写入方法外,我在网上找不到有关如何执行此操作的任何文档,这违背了在所有平台上共享相同config.json文件的目的。我只希望我的Android应用程序存储此config.json文件,并使该文件具有可读性和可写性。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我决定回答我自己的问题,并演示如何用代码完成它。在这个答案中,我同时使用Android资产和内部存储来操纵包含序列化对象的文件。

1)将文件复制到Xamarin.Android项目的Assets文件夹中,并将其“生成操作”更改为“ AndroidAsset”。这样可以确保文件最初与您的Android应用程序打包在一起。

2)在您的C#代码中,您真正想要的是从Android应用程序的内部存储而不是从AssetManager中读取和写入此文件(无论如何您都无法写入AssetManager,只能读取!)。因此,必须首先从AssetManager中提取文件,然后所有后续的读/写操作都将从内部存储中进行。

    /// <summary>
    /// This method will read the application settings from internal storage.  
    /// If it can't find it, it will use the default AndroidAsset version of 
    /// the appsettings.json file from this project's Asset folder.
    /// </summary>
    /// <returns></returns>
    public async Task<DefaultSettings> GetDefaultSettingsAsync()
    {
        var path = Application.Context.FilesDir.Path;
        if (File.Exists(Path.Combine(path, "appsettings.json")))
        {
            using (var sr = Application.Context.OpenFileInput("appsettings.json"))
            {
                using (var ms = new MemoryStream())
                {
                    await sr.CopyToAsync(ms);
                    var memoryBytes = ms.ToArray();
                    var content = System.Text.Encoding.Default.GetString(memoryBytes);
                    var defaultSettings = JsonConvert.DeserializeObject<DefaultSettings>(content);
                    return defaultSettings;
                }
            }
        }
        else
        {
            var result = await GetDefaultSettingsAssetAsync();
            return result;
        }
    }

    /// <summary>
    /// This method gets the appsettings.json file from the Android AssetManager, in the case
    /// where you do not have an editable appsettings.json file yet in your Android app's internal storage.
    /// </summary>
    /// <returns></returns>
    private static async Task<DefaultSettings> GetDefaultSettingsAssetAsync()
    {
        try
        {
            var assetsManager = MainActivity.Instance.Assets;

            using (var sr = assetsManager.Open("appsettings.json"))
            {
                using (var ms = new MemoryStream())
                {
                    await sr.CopyToAsync(ms);
                    var memoryBytes = ms.ToArray();
                    var content = System.Text.Encoding.Default.GetString(memoryBytes);
                    var defaultSettings = JsonConvert.DeserializeObject<DefaultSettings>(content);

                    // This will write the Asset to Internal Storage for the first time.  All subsequent writes will occur using SaveDefaultSettingsAsync.
                    using (var stream = Application.Context.OpenFileOutput("appsettings.json", FileCreationMode.Private))
                    {
                        await stream.WriteAsync(memoryBytes, 0, memoryBytes.Length);
                    }

                    return defaultSettings;
                }
            }
        }
        catch (Exception ex)
        {
            return new DefaultSettings();
        }
    }

    /// <summary>
    /// This method will save the DefaultSettings to your appsettings.json file in your Android App's internal storage.
    /// </summary>
    /// <param name="settings"></param>
    /// <returns></returns>
    public async Task SaveDefaultSettingsAsync(DefaultSettings settings)
    {
        using (var stream = Application.Context.OpenFileOutput("appsettings.json", FileCreationMode.Private))
        {
            var content = JsonConvert.SerializeObject(settings);
            var bytes = Encoding.Default.GetBytes(content);
            await stream.WriteAsync(bytes, 0, bytes.Length);
        }
    }