在共享存储 Xamarin 表单中保存文件

Tha*_*eem 1 xamarin.forms

我需要在android的共享存储中保存一个文件。我发现了这个链接=> https://developer.android.com/training/data-storage/shared/documents-files

我正在使用依赖项服务,并且能够成功将文件保存到所需位置。但我只能创建一个空白文件。我需要将一些内容写入该文件。实际上,几个小时前我使用 android 标签创建了一个线程,并得到了解决方案,我必须重写 OnActivityResult 方法并获取意图数据。现在我已经完成了,并且能够获取意图数据。但现在我不知道应该从意图中选择哪个路径以及如何使用所选路径打开文件以及如何将内容写入所选文件。任何 android + xamarin 专家应该能够帮助我..

android平台实现写服务的代码:

Activity _activity;
private static int CREATE_FILE = 6835;

public WriteFileService()
{
    _activity = CrossCurrentActivity.Current.Activity;
}

void IWriteService.WriteFile(string Content)
{
    Intent intent = new Intent(Intent.ActionCreateDocument);
    intent.AddCategory(Intent.CategoryOpenable);
    intent.SetType("application/txt");
    intent.PutExtra(Intent.ExtraTitle, "Invoice.txt");
    _activity.StartActivityForResult(intent, CREATE_FILE);
}
Run Code Online (Sandbox Code Playgroud)

重写的OnActivityResultMethod:

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    Toast.MakeText(Application.Context, "requestCode is " + requestCode, ToastLength.Short).Show();
    if (requestCode == 6835)
    {
        if (data != null)
        {
            Toast.MakeText(Application.Context,
                data.GetType().ToString(),
                ToastLength.Short).Show();

        }
    }

    base.OnActivityResult(requestCode, resultCode, data);
}
Run Code Online (Sandbox Code Playgroud)

这是来自 OnActivityResult 的意图数据的屏幕

在此输入图像描述

小智 5

在您的 Android 项目中使用它来将流保存到文件中:

public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
        {
            try
            {
                string root = null;
                //Get the root path in android device.
                if (Android.OS.Environment.IsExternalStorageEmulated)
                {
                    root = Android.OS.Environment.ExternalStorageDirectory.ToString();
                }
                else
                    root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                //Create directory and file 
                Java.IO.File myDir = new Java.IO.File(root + "/meusarquivos");
                myDir.Mkdir();

                Java.IO.File file = new Java.IO.File(myDir, fileName);

                //Remove if the file exists
                if (file.Exists()) file.Delete();

                //Write the stream into the file
                FileOutputStream outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
           }
            catch (Exception ex)
            {
                PostLog.AppCenterLogExcecao(ex, new Dictionary<string, string> { { "origem", "OrderViewModel - 159" } });
            }
        }
Run Code Online (Sandbox Code Playgroud)

在您的共享代码中:

await DependencyService.Get<ISave>().SaveAndView(OrderId.ToString() + ".pdf", "application/pdf", stream);
Run Code Online (Sandbox Code Playgroud)

使用代码之前请务必请求权限。