How to get the list of files with specific extension in Xamarin Android?

元气小坏坏 提交于 2021-01-29 19:02:18

问题


I need suggestion on getting a list of PDF files from the external storage in android device


回答1:


1.You could traverse the folder and filter the PDF files:

public void Search_Pdf_Dir(File dir)
    {
        string pdfPattern = ".pdf";

        File[] FileList = dir.ListFiles();

        if (FileList != null)
        {
            for (int i = 0; i < FileList.Length; i++)
            {

                if (FileList[i].IsDirectory)
                {
                    Search_Pdf_Dir(FileList[i]);
                }
                else
                {
                    if (FileList[i].Name.EndsWith(pdfPattern))
                    {
                        //here you have that file.

                    }
                }
            }
        }
    }

then you could call like Search_Pdf_Dir(Android.OS.Environment.ExternalStorageDirectory);

2.use MediaStore - Uri to query all types of files :

ContentResolver cr = ContentResolver;
Android.Net.Uri uri = MediaStore.Files.GetContentUri("external");

// every column, although that is huge waste, you probably need
// BaseColumns.DATA (the path) only.
string[] projection = null;
string selectionMimeType = MediaStore.Files.FileColumns.MediaType + "=?";
string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension("pdf");
string[] selectionArgsPdf = new string[] { mimeType };
string sortOrder = null;
var allPdfFiles = cr.Query(uri, projection, selectionMimeType, selectionArgsPdf, sortOrder);
while (allPdfFiles.MoveToNext())
    {
        int column_index = allPdfFiles.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
        string filePath = allPdfFiles.GetString(column_index);//the pdf path
    }


来源:https://stackoverflow.com/questions/60727368/how-to-get-the-list-of-files-with-specific-extension-in-xamarin-android

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