Search code examples
urivala

What's the best way to get a file's basename from an URI, in Vala?


I can think of two ways: first, I could just manipulate the string itself; strip everything that precedes the last "/". Or, I could use the URI to get a File object, then call query_info().get_display_name().

The first doesn't feel right, while the second results in two objects being created. What is the best practice to follow here?


Solution

  • The second way (using GLib.File) is probably the most robust, but...

    If what you have is really a path, not a URI (e.g.., /home/foo/bar not file:///home/foo/bar) you can just use GLib.Path.get_basename:

    GLib.Path.get_basename ("/home/foo/bar");
    

    Because characters in a URI can be encoded (e.g., %20 instead of a space), if you really have a URI you may need to unescape the string first:

    GLib.Path.get_basename (GLib.Uri.unescape_string ("file:///home/foo/bar%20baz"));