Get a File Extension from Filename | VB.NET

In VB.NET, you can extract the file extension from a filename by using the Path.GetExtension method from the System.IO namespace. This method will return the extension portion of a file path or filename as a string.

Path.GetExtension

Imports System.IO Module Program Sub Main() Dim filePath As String = "C:\Example\mydocument.txt" ' Get the file extension Dim extension As String = Path.GetExtension(filePath) ' Display the file extension Console.WriteLine("File Extension: " & extension) End Sub End Module ' Output: File Extension: txt

You can replace the filePath variable with the actual filename or path you want to extract the extension from. This method is useful when you need to work with file manipulation or categorization based on file types.

The Path.GetExtension method is a part of the System.IO namespace in .NET, and it is used to extract the extension of a file from a file path or filename as a string.

Using Substring

Also, To get the extension from a filename in VB.NET, you can use the following code:

Imports System.IO Public Sub GetExtension(filename As String) As String Dim index As Integer = filename.LastIndexOf(".") If index > -1 Then Dim extension As String = filename.Substring(index + 1) Return extension Else Return "" End If End Sub

The LastIndexOf() method returns the index of the last occurrence of a specified character in a string.

The Substring() method returns a substring of a string starting at a specified index.

Here is an example of how to use the GetExtension() function:

Public Sub Main() Dim filename As String = "MyFile.txt" Dim extension As String = GetExtension(filename) Console.WriteLine("The extension is: {0}", extension) End Sub Output: The extension is: txt

You can use the GetExtension() function to get the extension of any filename, regardless of the operating system.

Full Source | VB.Net
Imports System.IO Public Class Program Public Shared Sub Main() Dim filename As String = "MyFile.txt" Dim extension As String = GetExtension(filename) Console.WriteLine("The extension is: {0}", extension) End Sub Public Shared Function GetExtension(filename As String) As String Dim index As Integer = filename.LastIndexOf(".") If index > -1 Then Dim extension As String = filename.Substring(index + 1) Return extension Else Return "" End If End Function End Class

Conclusion

you can retrieve the file extension from a filename by using the Path.GetExtension method from the System.IO namespace. This method takes a file path or filename as input and returns the file extension as a string, including the period (.) character. It is a convenient way to work with and categorize files based on their extensions in your VB.NET applications.