Change file name of image path in C# Change file name of image path in C# asp.net asp.net

Change file name of image path in C#


This following code snippet changes the filename and leaves the path and the extenstion unchanged:

string path = @"photo\myFolder\image.jpg";string newFileName = @"image-resize";string dir = Path.GetDirectoryName(path);string ext = Path.GetExtension(path);path =  Path.Combine(dir, newFileName + ext); // @"photo\myFolder\image-resize.jpg"


You can use Path.GetFileNameWithoutExtension method.

Returns the file name of the specified path string without the extension.

string path = @"photo\myFolder\image.jpg";string file = Path.GetFileNameWithoutExtension(path);string NewPath = path.Replace(file, file + "-resize");Console.WriteLine(NewPath); //photo\myFolder\image-resize.jpg

Here is a DEMO.


Or the File.Move method:

System.IO.File.Move(@"photo\myFolder\image.jpg", @"photo\myFolder\image-resize.jpg");

BTW: \ is a relative Path and / a web Path, keep that in mind.