Android Question Get name of File from ContentChooser result?

JohnC

Well-Known Member
Licensed User
I wish to obtain the filename of the selected file from the content chooser.

For example, content chooser could return:

B4X:
Wait For CC_Result (Success As Boolean, Dir As String, FileName As String)
Directory = "ContentDir"
Filename = "content://com.android.externalstorage.documents/document/0000-0000%3AASLogo.jpg"

I know that the filename that I chose is "ASLogo.jpg".

And I see that there is a colon (%3A) right before the filename at the end of the string.

So, my questions are:

1) Is that last %3A guaranteed to ALWAYS be included in a content string and be the last delimiter before the filename?
2) And if not, what is a good way to get the filename returned from CC no matter what format it returns?
 

JohnC

Well-Known Member
Licensed User
OK, I created this routine to extract the filename, but it is making a few assumptions:

1) That real file paths will always start with "/"
2) That content uri's will always have "%3A" at the end, before the file name.

B4X:
Sub GetFileNameFromContentResult(UriString As String) As String
    If UriString.StartsWith("/") Then 'If the user used a file manager to choose file
        Return UriString.SubString2(UriString.LastIndexOf("/")+3,UriString.Length)
    else if UriString.StartsWith("content:") Then
        If UriString.IndexOf("%3A") > -1 Then
            Return UriString.SubString2(UriString.LastIndexOf("%3A")+3,UriString.Length)
        Else if UriString.IndexOf("/") > -1 Then
            Return UriString.SubString2(UriString.LastIndexOf("/")+3,UriString.Length)
        Else
            Return UriString
        End If
    Else
        Return UriString
    End If
End Sub
But, are these assumptions correct, or will there be exceptions?
 
Last edited:

Erel

Administrator
Staff member
Licensed User
But, are these assumptions correct, or will there be exceptions?
They are not correct.

There is no reliable way to get the file name. Content providers are not expected to return the file name in the URI.
 
Top