My image URL is like this:
photo\myFolder\image.jpg
I want to change it so it looks like this:
photo\myFolder\image-resize.jpg
Is there any short way to do it?
My image URL is like this:
photo\myFolder\image.jpg
I want to change it so it looks like this:
photo\myFolder\image-resize.jpg
Is there any short way to do it?
This following code snippet changes the filename and leaves the path and the extenstion unchanged:
public static string ChangeFilename(string filepath, string newFilename)
{
// filepath = @"photo\myFolder\image.jpg";
// newFileName = @"image-resize";
string dir = Path.GetDirectoryName(filepath); // @"photo\myFolder"
string ext = Path.GetExtension(filepath); // @".jpg"
return 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.
images\myFolder\image.jpg your method will also change the imagespart of the path to image-resizes. I would get the directory path, the filename and the extension separately, change the filename and rebuild a path from all these elements.I would use a method like this:
private static string GetFileNameAppendVariation(string fileName, string variation)
{
string finalPath = Path.GetDirectoryName(fileName);
string newfilename = String.Concat(Path.GetFileNameWithoutExtension(fileName), variation, Path.GetExtension(fileName));
return Path.Combine(finalPath, newfilename);
}
In this way:
string result = GetFileNameAppendVariation(@"photo\myFolder\image.jpg", "-resize");
Result: photo\myFolder\image-resize.jpg
You can try this
string fileName = @"photo\myFolder\image.jpg";
string newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) +
"-resize" + fileName.Substring(fileName.LastIndexOf('.'));
File.Copy(fileName, newFileName);
File.Delete(fileName);