zey*_*zey 11 c# asp.net string path
如果我的图片网址是喜欢的,
photo\myFolder\image.jpg
Run Code Online (Sandbox Code Playgroud)
我想改变的是喜欢,
photo\myFolder\image-resize.jpg
Run Code Online (Sandbox Code Playgroud)
有没有简短的方法呢?
Doo*_*nky 14
以下代码片段更改了文件名,并保持路径和扩展名不变:
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"
Run Code Online (Sandbox Code Playgroud)
你可以使用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
Run Code Online (Sandbox Code Playgroud)
这是一个DEMO.
我会使用这样的方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
这样:
string result = GetFileNameAppendVariation(@"photo\myFolder\image.jpg", "-resize");
Run Code Online (Sandbox Code Playgroud)
结果:photo\myFolder\image-resize.jpg