To change the File extension in C# and VB.NET you can use the following snippet.

Sample C#

public static FileInfo ChangeExtension(FileInfo file, string newExtension)
{
	if (!newExtension.StartsWith("."))
	{
		newExtension = "." + newExtension;
	}
	var fileName = string.Concat(Path.GetFileNameWithoutExtension(file.FullName), newExtension);
	if (File.Exists(fileName))
	{
		File.Delete(fileName);
	}
	File.Move(file.FullName,fileName);
	if (File.Exists(fileName))
	{
		File.Delete(file.FullName);
	}
	return new FileInfo(fileName);
}

Sample VB.NET

Public Shared Function ChangeExtension(file__1 As FileInfo, newExtension As String) As FileInfo
	If Not newExtension.StartsWith(".") Then
		newExtension = Convert.ToString(".") & newExtension
	End If
	Dim fileName = String.Concat(Path.GetFileNameWithoutExtension(file__1.FullName), newExtension)
	If File.Exists(fileName) Then
		File.Delete(fileName)
	End If
	File.Move(file__1.FullName, fileName)
	If File.Exists(fileName) Then
		File.Delete(file__1.FullName)
	End If
	Return New FileInfo(fileName)
End Function

One thought on “How to change the File extension in C# and VB.NET”

Leave a Reply