Ali123
Ali123

Reputation: 797

Xamarin forms Deleting an image returns true, but I can still see the image in the file system?

I am using Dependency service to delete a file that I just took using the media.plugin for Xamarin forms:

var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
        Directory = "CameraTakenPhotos",
        SaveToAlbum = false,
        CompressionQuality = 75,
        CustomPhotoSize = 50,
        PhotoSize = PhotoSize.MaxWidthHeight,
        MaxWidthHeight = 2000,
        DefaultCamera = CameraDevice.Rear
    });

if (file == null)
    return;
var ImagePath = file.Path;
await DisplayAlert("File Location", file.Path, "OK");

try
{
    var imageExists = Helpers.StorageHelper.FileExists(ImagePath);
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine("Error occured while checking if image is available: " + ex);
}

image.Source = ImageSource.FromStream(() =>
{
    var stream = file.GetStream();
    file.Dispose();
    return stream;
});

//deleting the image
try
{
    var deletationResutl = Helpers.StorageHelper.DeleteFileByPath(ImagePath);
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine("Error while deleting the image " + ex);
}

The DeleteFileByPath function returns true=> file is deleted. but I can still see the image on my phone using ES File Explorer

the implementation for the method is:

public bool DeleteFileByPath(string filePath)
{
    File.Delete(filePath);

    if (File.Exists(filePath))
        return false;//not deleted
    else
        return true;//deleted
}

Could someone help me with this issue, please?

UPDATE#1: I created another method to check if the image is there or not. It's telling me that the image is there!

So, the deletion has failed, but it told me that it was deleted the first time. This is the method I developed for testing:

var imageExists = Helpers.StorageHelper.FileExists(ImagePath);

if(imageExists)
    await DisplayAlert("Confirmation", "Image is there", "Ok");
else
    await DisplayAlert("Confirmation", "No image was found", "Ok");

UPDATE#2: When I try to delete an image that doesn't exists, I am getting a false which is the expected behavior.

I am confused and lost. I will try with iOS and see if it's a bug or something

UPDATE#3: The same behavior is occurring for iOS.

Upvotes: 1

Views: 2155

Answers (1)

Ali123
Ali123

Reputation: 797

This is very eqmberssing but apparently it was a typo in the helper class. I was calling the method "FileExists" instead of "DeleteFile"

This is the correct helper method:

public static bool DeleteFileByPath(string filePath)
    {
        return Xamarin.Forms.DependencyService.Get<IFileHelper>().DeleteFileByPath(filePath);
    }

Upvotes: 2

Related Questions