我的图片网址是这样的:
photo\myFolder\image.jpg
我想改变它,使它看起来像这样:
photo\myFolder\image-resize.jpg
有什么捷径可以做到吗?
以下代码片段更改了文件名并保持路径和扩展名不变:
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"
你可以使用Path.GetFileNameWithoutExtension
方法。
返回指定路径字符串的文件名,不带扩展名。
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
这是一个演示。
或 File.Move 方法:
System.IO.File.Move(@"photo\myFolder\image.jpg", @"photo\myFolder\image-resize.jpg");
顺便说一句:\ 是相对路径和 / 网络路径,请记住这一点。
这是我用于文件重命名的
public static string AppendToFileName(string source, string appendValue)
{
return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}
我会使用这样的方法:
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);
}
这样:
string result = GetFileNameAppendVariation(@"photo\myFolder\image.jpg", "-resize");
结果:photo\myFolder\image-resize.jpg
你可以试试这个
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);
试试这个
File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");