Search code examples
c#androidxamarin.androidstorage-access-framework

Store file with the storage access framework on Google Drive


I want to store a file with the Android storage access framework. My test code should store a file "hallo1" with the size of 1000000. But only a file "hallo1" with the filesize 0 will be created. I get no error message. The saving on local disc and sd-card works fine only google drive does not work. The Code:

        protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button>(Resource.Id.myButton);

        button.Click += delegate
        {
            Intent intentCreate = new Intent(Intent.ActionCreateDocument);
            intentCreate.AddCategory(Intent.CategoryOpenable);
            intentCreate.SetType("audio/*");
            intentCreate.PutExtra(Intent.ExtraTitle, "hallo" + count);
            StartActivityForResult(intentCreate, 1);

            count++;
        };
    }

    protected override  void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        var stream = this.ContentResolver.OpenOutputStream(data.Data, "w");
        var b = new byte[1000000];
        stream.Write(b, 0, b.Length);
        stream.Flush();
        stream.Close();

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

Filepicker from the android storage access framework

Enter the filename (default "hallo1" from the code)

data.Data gives an internal Android.Net.Uri back.

Somebody an idea where is the problem?


Solution

  • I found a solution:

            protected override  void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
    
            // this works fine:
            using (System.IO.Stream stream = this.ContentResolver.OpenOutputStream(data.Data, "w"))
            {
                using (var javaStream = new Java.IO.BufferedOutputStream(stream))
                {
                    var b = new byte[1000000];
                    javaStream.Write(b, 0, b.Length);
                    javaStream.Flush();
                    javaStream.Close();
                }
            }
    
            // the direct writing on the System.IO.Stream failed:
            //using (System.IO.Stream stream = this.ContentResolver.OpenOutputStream(data.Data, "w"))
            //{
            //    var b = new byte[1000000];
            //    stream.Write(b, 0, b.Length);
            //    stream.Flush();
            //    stream.Close();
            //}
    
            base.OnActivityResult(requestCode, resultCode, data);
        }
    

    Somebody a idea why this works and the direct writing with the System.IO.Stream failed?