How to get the filename of a shared WhatsApp text file in Xamarin Forms Android?

154 views Asked by At

I used to use the following method to get the name of a text file shared via WhatsApp to my app:

string GetIntentFilename(Android.Net.Uri uri)
{
    string filename;
    string temp;

    using (var c1 = ContentResolver.Query(uri, null, null, null, null))
    {
        c1.MoveToFirst();
        temp = c1.GetString(0);

        filename = temp.Substring(temp.LastIndexOf(":") + 1);
    }

    return filename.Trim();
}

If I shared a file 123.txt, the above method would return "123.txt"

Recently however it has been returning me a weird name, similar to the following: "DOC-20230109-WA0008."

I've tried sharing the file with other apps and they successfully extract the 123.txt filename, so I'm sure the information exists somewhere in the intent, but I don't know how to get it.

Any ideas?

1

There are 1 answers

8
Liyun Zhang - MSFT On

Refer to this answer about Android Studio get shared file, name of Uri, from whatsapp to my app, you can try the following code:

string GetIntentFilename(Android.Net.Uri uri)
{
    string filename;

    using (var c1 = ContentResolver.Query(uri, null, null, null, null))
    {
     //  var index = c1.GetColumnIndex(OpenableColumns.DisplayName);

     //  the OpenableColumns.DisplayName has been deprecated, you can try the next line code

       var index = c1.GetColumnIndex(IOpenableColumns.DisplayName);
       c1.MoveToFirst();
       filename = c1.GetString(index);
                }
    return filename;
}