'Xamarin System.ObjectDisposedException: 'Cannot access a closed Stream.'

I'm working on a mobile project with Xamarin Forms and I have this error in particulary case but, it's impossible to use the debuger to fix it.

System.ObjectDisposedException: 'Cannot access a closed Stream.'

Little bit of context: I am in a TabPage ( from DevExpress ) and when I navigate through the tab, this error occurs sometimes.

So I use a little bit of Stream object in my code, but honestly I don't know where could be the error.

So here is my code with Stream object

public async Task<bool> TakePhotoAsync()
        {
            try
            {
                var photo = await MediaPicker.CapturePhotoAsync();
                await LoadPhotoAsync(photo);
                Console.WriteLine($"CapturePhotoAsync COMPLETED: {PhotoPath}");
                return true;
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                Console.WriteLine("Device not supported");
                return false;
            }
            catch (PermissionException pEx)
            {
                Console.WriteLine("Permission non accordée");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
                return false;
            }
        }

        public async Task LoadPhotoAsync(FileResult photo)
        {
            // canceled
            string path = "";
            if (photo == null)
            {
                this.PhotoPath = null;
                return;
            }
            // save the file into local storage
            using (var stream = await photo.OpenReadAsync())
                DependencyService.Get<IDeviceDependency>().SaveImage(stream, "photo", $"{bon.DOSSIER.DODOS}_BT_{bon.CLE_DOSPRESTA_BON}_{NbPhoto++}.png", ref path);
            this.PhotoPath = path;
        }
public class MyDependencyService: IDeviceDependency
    {
        public bool SaveImage(Stream image, string directory, string name, ref string PhotoPath)
        {
            string path = Android.App.Application.Context.GetExternalFilesDir(directory).AbsolutePath;

            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            if (image != null && image.CanWrite)
            {
                MemoryStream ms = new MemoryStream();
                image.CopyTo(ms);

                path = System.IO.Path.Combine(path, name);
                PhotoPath = path;
                File.WriteAllBytes(path, ms.ToArray());
                return true;
            }

            return false;
        }
        public bool SaveImage(Stream image, string directory, string name)
        {
            string value = "";
            return this.SaveImage(image, directory, name, ref value);
        }

        public FileStream ShowImage(string directory, string name)
        {
            string path = System.IO.Path.Combine(Android.App.Application.Context.GetExternalFilesDir(directory).AbsolutePath, name);
            FileStream stream = null;

            if (File.Exists(path))
            {
                try
                {
                    stream = new FileStream(path, FileMode.Open);
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }

            return stream;
        }

        public bool DeleteFile(string directory, string name)
        {
            string path = System.IO.Path.Combine(Android.App.Application.Context.GetExternalFilesDir(directory).AbsolutePath, name);
            if (File.Exists(path))
            {
                File.Delete(path);
                return true;
            }
            return false;
        }
        public Stream ResizeImageAndroid(byte[] imageData, double width, double height)
        {
            if ( imageData.Length > 0 )
            {
                // Load the bitmap
                Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
                Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, false);

                MemoryStream ms = new MemoryStream();
                resizedImage.Compress(Bitmap.CompressFormat.Png, 100, ms);
                return new MemoryStream(ms.ToArray());
            }
            return null;
        }

        public string GetExternalXMLPath(string name)
        {
            return System.IO.Path.Combine(Android.App.Application.Context.GetExternalFilesDir("xml").AbsolutePath, name);
        }
protected override void OnAppearing()
        {
            this.Model.ExecuteRefreshCommand();
            FileStream stream = DependencyService.Get<IDeviceDependency>().ShowImage("signature", "76");
            Stream streamImg;

            double rapport = this.ImgSignature.HeightRequest/Signature.HAUTEUR_SIGNATURE;

            if (stream != null && stream.CanWrite)
            {
                MemoryStream ms = new MemoryStream();
                stream.CopyTo(ms);
                streamImg = DependencyService.Get<IDeviceDependency>().ResizeImageAndroid(ms.ToArray(), rapport*(App.Current.MainPage.Width - 30),
                                                                                                        rapport*Signature.HAUTEUR_SIGNATURE);

                if (streamImg != null && streamImg.CanRead)this.ImgSignature.Icon = ImageSource.FromStream(() => streamImg);
            }

            base.OnAppearing();
        }

UPDATE I also find the call stack error for [External Code] look like this

    0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal  C#
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.Diagnostics/Debugger.cs:125,4   C#
0x33 in Android.Runtime.DynamicMethodNameCounter.84 C#
0xD in System.IO.MemoryStream.EnsureNotClosed at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs:121,17  C#
0x4F in System.IO.MemoryStream.Read at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/IO/MemoryStream.cs:369,13    C#
0x9 in Android.Runtime.InputStreamAdapter.Read at /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/InputStreamAdapter.cs:38,4 C#
0x23 in Java.IO.InputStream.n_Read_arrayBII at /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-30/mcw/Java.IO.InputStream.cs:251,4 C#
0x23 in Android.Runtime.DynamicMethodNameCounter.84 C#
0xFFFFFFFFFFFFFFFF in Java.Interop.NativeMethods.java_interop_jnienv_call_static_object_method_a    C#
0x59 in Java.Interop.JniEnvironment.StaticMethods.CallStaticObjectMethod    C#
0x1A in Java.Interop.JniPeerMembers.JniStaticMethods.InvokeObjectMethod C#
0x2F in Android.Graphics.BitmapFactory.DecodeStream at /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-30/mcw/Android.Graphics.BitmapFactory.cs:825,5  C#
0x6 in Android.Graphics.BitmapFactory. at /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-30/mcw/Android.Graphics.BitmapFactory.cs:835,58  C#
0x11 in System.Threading.Tasks.Task<Android.Graphics.Bitmap>.InnerInvoke at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:534,17    C#
0x1 in System.Threading.Tasks.Task.Execute at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319,17   C#
0x6 in System.Threading.Tasks.Task.ExecutionContextCallback at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2463,13  C#
0x73 in System.Threading.ExecutionContext.RunInternal at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:968,17   C#
0x4 in System.Threading.ExecutionContext.Run at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:910,13    C#
0x38 in System.Threading.Tasks.Task.ExecuteWithThreadLocal at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/corert/Task.cs:72,6    C#
0x50 in System.Threading.Tasks.Task.ExecuteEntry at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2385,17 C#
0x2 in System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2334,13  C#
0x75 in System.Threading.ThreadPoolWorkQueue.Dispatch at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:899,29 C#
0x0 in System.Threading._ThreadPoolWaitCallback.PerformWaitCallback at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1261,13  C#


Solution 1:[1]

I find an issue, According to the [External error], the error occurs from the Bitmap.Decode function. So I just delete this part of code and replace my Simplebutton with Icon by an ImageIcon and the resize was automatic so don't need of Bitmap.

Regards for your help!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1