Thameem
Thameem

Reputation: 756

Saving a file in shared storage Xamarin forms

I need to save a file in the shared storage of android. I came across this link => https://developer.android.com/training/data-storage/shared/documents-files

I am using the dependency service and I am able to successfully save a file to desired location. But I am able to create only a blank file. I need to write some content into that file. Actually I created a thread few hours ago with android tag and got the solution where I had to override the OnActivityResult method and get the intent data. Now I have done it and I am able to get the intent data. But Now I dont know which path should i choose from the intent and how to open the file using the chosen path and how to write content into that chosen file. Any android + xamarin expert should be able to help me..

The android platform code to implement the write service:

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);
}

The overriden 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);
}

This is the screen of the Intent Data from OnActivityResult

enter image description here

Upvotes: 1

Views: 6391

Answers (2)

LeoSouza
LeoSouza

Reputation: 527

Use this in your Android project to save a stream to file:

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" } });
            }
        }

And in your shared code:

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

Be sure to ask for the permissions before using the code.

Upvotes: 5

Thameem
Thameem

Reputation: 756

To save the file. ive used this code

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if (requestCode == 6835)
    {
        if (data != null)
        {
            Android.Net.Uri uri = Android.Net.Uri.Parse(data.DataString);
            var stream = ContentResolver.OpenOutputStream(uri, "w");
            byte[] byteArray = Encoding.UTF8.GetBytes("Hi Thameem. I am your file.");
            MemoryStream stream1 = new MemoryStream(byteArray);
            stream1.CopyTo(stream);
            stream.Flush();
            stream.Close();
            Toast.MakeText(Application.Context,
                "The file has been exported successfully",
                ToastLength.Short).Show();
        }
    }

    base.OnActivityResult(requestCode, resultCode, data);
}

Upvotes: 0

Related Questions