get file extension from file name

Maybe a stupid question, but I don’t see a function to do this…

Is there an easy way to pull the extension out of a file name?
Or should I just take the characters after the last dot?

thanks

gert

Yes, you need your own function. There are a number of ways to do it, but this should work.

dim ext as string

dim parts() as string = filename.Split( "." )
if parts.Ubound > 0 and parts( 0 ) <> "" then
  dim lastPart as string = parts.Pop
  if lastPart.InStr( " " ) = 0 then
    ext = lastPart
  end if
end if

return ext

If a file starts with a dot, it will not be considered an extension. Note too that if the last part contains a space, it will not be considered an extension. This matches what the Finder on the Mac but might not meet your requirements.

If you have MBS plugins you can use folderitem.nameextensionMBS.

Else characters after the last dot.

There are many variants of this, but I use this to get the last dot position.

Function InstrRev(Instring as string, Delim as string) As Integer Dim i as integer If instr(Instring,delim) < 1 then return 0 end if For i=len(Instring) downto 1 If instr(i,Instring,delim) > 0 then return instr(i,Instring,delim) end if next return 0 End Function

Or this regular expression pattern. :slight_smile:

^[^.].*\\.\\K\\S+

Thanks a lot, all. All this is working fine!
Stupid I spent so much time looking for a function because I did not know it did not exist.
Grateful for your fast reply, all.

You can also create an Extends method in a module so this can become a “part” of FolderItem.

In a module, create the following method as Global:

Function NameExtension (Extends f As FolderItem) As String
  dim ext as string

  dim parts() as string = f.Name.Split( "." )
  if parts.Ubound > 0 and parts( 0 ) <> "" then
    dim lastPart as string = parts.Pop
    if lastPart.InStr( " " ) = 0 then
      ext = lastPart
    end if
  end if

  return ext
End Function

Then you can do things like “ext = f.NameExtension”.

[quote=263057:@Kem Tekinay]Or this regular expression pattern. :slight_smile:

^[^.].*\\.\\K\\S+ [/quote]

Showoff! :wink:

Thanks all !

I was yesterday in the exact inverse: I wanted the file name without the extension. My previous code was (stupid) buggy: I certainly was in a hurry when I coded it… (if there is a home url in the file name - to set the source of the data in the file - the dots in it displayed the bug [or simply a dot inthe file name that is not the one before the extension).

The process to remove the extension was to detect where it is ;-:slight_smile:

Then, I used left to get what I wanted !