Reputation: 6105
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?
Upvotes: 28
Views: 34337
Reputation: 1188
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"
}
Upvotes: 30
Reputation: 5122
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
Upvotes: 5
Reputation: 434
This is what i use for file renaming
public static string AppendToFileName(string source, string appendValue)
{
return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}
Upvotes: 3
Reputation: 8726
try this
File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");
Upvotes: 0
Reputation: 4172
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);
Upvotes: 1
Reputation: 98740
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.
Upvotes: 7
Reputation: 5150
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.
Upvotes: 2