How to delete files using xamarin forms

柔情痞子 提交于 2021-01-29 11:28:39

问题


I tried to delete file from specific directory(Folder) but it doesn't work for me

this is my code

DeletePhoto.Clicked += async (sender, args) =>
            {
                var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
                {
                    PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

                });


                if ( file != null)
                {
                    if (File.Exists(file.Path))
                    {
                        DependencyService.Get<IFileManager>().DeleteFile(file.Path);
                    }
                    file.Dispose();

                }
            };

In android

  public class FileManager : IFileManager
        {
            public void DeleteFile(string source)
            {
                File.Delete(source);
            }
        }

IFileManager Interface

 public interface IFileManager
    {
        void DeleteFile(string source);
    }

In mainfest permisson is given but something didn't happen and i find the file which i deleted


回答1:


The problem is caused by PickPhotoAsync()method, this method is saving a COPY of the image in the blow directory:

"/storage/emulated/0/Android/data/{package name}/files/Pictures/temp/***.jpg"

you can debug to find this and you can check this issue of MediaPlugin by this

So when you use PickPhotoAsync()method to select a file, the actual file you have deleted is the copy in the temp directory.

If you want to delete the original file, you will have to change the parameter of

DeleteFile(string source) method to the original path as follows:

string path= "/storage/emulated/0/Android/data/{package name}/files/Pictures/Test/***.jpg";

DeleteFile(path);



回答2:


What worked for me , You'll some dependency injection on android:

using Android.Content; using Android.Provider; using System;

     public bool DeleteFile(string filePath)
    {
        try
        {
            Context context = Android.App.Application.Context;
            Java.IO.File file = new Java.IO.File(filePath);

            string where = MediaStore.MediaColumns.Data + "=?";
            string[] selectionArgs = new string[] { file.AbsolutePath };
            ContentResolver contentResolver = context.ContentResolver;
            Android.Net.Uri filesUri = MediaStore.Files.GetContentUri("external");

            if (file.Exists())
            {
                contentResolver.Delete(filesUri, where, selectionArgs);
                return true;
            }
            return false;
        }
        catch (Exception e)
        { 
            return false;
        }
    }


来源:https://stackoverflow.com/questions/54330202/how-to-delete-files-using-xamarin-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!