21

我的图片网址是这样的:

photo\myFolder\image.jpg

我想改变它,使它看起来像这样:

photo\myFolder\image-resize.jpg

有什么捷径可以做到吗?

4

7 回答 7

23

以下代码片段更改了文件名并保持路径和扩展名不变:

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"
于 2016-05-23T00:11:00.557 回答
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

这是一个演示

于 2013-06-19T06:33:24.350 回答
2

或 File.Move 方法:

System.IO.File.Move(@"photo\myFolder\image.jpg", @"photo\myFolder\image-resize.jpg");

顺便说一句:\ 是相对路径和 / 网络路径,请记住这一点。

于 2013-06-19T06:36:04.853 回答
2

这是我用于文件重命名的

public static string AppendToFileName(string source, string appendValue)
{
    return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}
于 2017-01-26T05:27:39.417 回答
2

我会使用这样的方法:

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

于 2018-10-31T08:26:24.237 回答
1

你可以试试这个

 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);
于 2013-06-19T06:39:46.020 回答
0

试试这个

File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");
于 2013-06-19T06:36:05.673 回答