且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Xamarin Android 中获取具有特定扩展名的文件列表?

更新时间:2022-11-28 11:26:25

1.可以遍历文件夹,过滤PDF文件:

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.

                    }
                }
            }
        }
    }

然后你可以调用 Search_Pdf_Dir(Android.OS.Environment.ExternalStorageDirectory);

2.使用 MediaStore - Uri 查询所有类型的文件:

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
    }