在 C# 中更改图像路径的文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17184333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change file name of image path in C#
提问by zey
If my image URL is likes ,
如果我的图片网址是 likes ,
photo\myFolder\image.jpg
How I want to change is likes ,
我想改变的方式是喜欢,
photo\myFolder\image-resize.jpg
Is there any short way to do it ?
有什么捷径可以做到吗?
采纳答案by Soner G?nül
You can use Path.GetFileNameWithoutExtensionmethod.
您可以使用Path.GetFileNameWithoutExtension方法。
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.
这是一个演示。
回答by Smartis
Or the File.Move method:
或者 File.Move 方法:
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.
顺便说一句:\ 是相对路径和 / 网络路径,请记住这一点。
回答by sangram parmar
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");
回答by Debajit Mukhopadhyay
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);
回答by Doomjunky
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"
回答by Joel Fleischman
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)}";
}
回答by MAXE
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
结果:photo\myFolder\image-resize.jpg

