在C#中更改图像路径的文件名

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)


Son*_*nül 8

你可以使用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.

  • 如果路径是`images\myFolder\image.jpg`,你的方法也会将路径的`images`part改为`image-resizes`.我将分别获取目录路径,文件名和扩展名,更改文件名并重建所有这些元素的路径. (24认同)

MAX*_*AXE 5

我会使用这样的方法:

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