'Xamarin: How to delete files using CrossFilePicker Xamarin Forms

I am using the following code to pick a file using CrossFilePicker in Xamarin forms. Goal is to delete the selected file in Xamarin.Android project, file still intact after running the command.

            FileData filedata = await CrossFilePicker.Current.PickFile();
            Android.Net.Uri uri = Android.Net.Uri.Parse(filedata.FilePath);

            Java.IO.File file = new Java.IO.File(uri.Path);
            File.Delete(file.AbsolutePath);
            await DisplayAlert("✅", file.AbsolutePath, "Okay");

When using the DisplayAlert to check the filepath, I saw the below path, but file doesn't delete!!

          /storage/emulated/0/documents/SalesRecords.db3


Solution 1:[1]

I recommend you to use Essentials.FilePicker, it allows you to pick file with code like:

async Task<FileResult> PickAndShow(PickOptions options)
{
    try
    {
        var result = await FilePicker.PickAsync(options);
        if (result != null)
        {
            Text = $"File Name: {result.FileName}";
            if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
                result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
            {
                var stream = await result.OpenReadAsync();
                Image = ImageSource.FromStream(() => stream);
            }
        }
        
        return result;
    }
    catch (Exception ex)
    {
        // The user canceled or something went wrong
    }
    
    return null;
}

And once you get the result you can delete the file like:

    FileResult file= await PickAndShow(PickOptions.Default);
    File.Delete(file.FullPath);

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 Adrain Zhu -MSFT