Search code examples
xamaringoogle-drive-apiinputstreamdrive

Google Drive: Xamarin - Android GetInputStream - can only be called once per Content Instance


I have the Google drive opened and the files are selectable. After clicking the confirmation button, I will have a response and call the InputStream and start reading the file. This was my code which read the InputStream.

var pendingResult = driveFile.OpenAsync(GoogleApiClient, DriveFile.ModeReadOnly, this)
            .ContinueWith((resultTask) =>
            {
                var driveContentResults = resultTask.Result;
                var driveContent = driveContentResults.DriveContents;

                if (_dialog != null && _dialog.IsShowing)
                    _dialog.Dismiss();

                if (driveContentResults.Status.IsSuccess)
                {
                    if (FileReadyCallback != null)
                    { 
                        var length = driveContent.InputStream.Length;
                        //var data = new byte[length];
                        //driveContent.InputStream.Read(data, 0, data.Length);
                        //FileReadyCallback(this, data);
                    }
                    //var absolutePath = FileUtilities.SaveStreamToDownloadDirectory(driveContent.InputStream, Guid.NewGuid() + ".pdf");
                    //SendResultToCallingActivity(absolutePath);
                }

            });

When the application reached to driveContent.InputStream.Length, the breakpoint showed me that the InputStream can only be called once per Content Instance. In the code, that line is my first call of the input stream.


Solution

  • As the error says, instead of calling driveContent.InputStream every time, make a variable named input and assign driveContent.InputStream, then use input to read bytes, get length or other methods.

    var input = driveContent.InputStream
    

    and then replace with

    var length = input.Length;
    

    and

    input.Read(data, 0, data.Length);