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

rkttyhzu  于 5个月前  发布在  .NET
关注(0)|答案(7)|浏览(58)

我的图片URL是这样的:

photo\myFolder\image.jpg

字符串
我想把它改成这样:

photo\myFolder\image-resize.jpg


有什么捷径吗?

vlurs2pr

vlurs2pr1#

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

public static string ChangeFilename(string filepath, string newFilename)
{
    // filepath = @"photo\myFolder\image.jpg";
    // newFileName = @"image-resize";

    string dir = Path.GetDirectoryName(filepath);    // @"photo\myFolder"
    string ext = Path.GetExtension(filepath);        // @".jpg"

    return Path.Combine(dir, newFilename + ext); // @"photo\myFolder\image-resize.jpg"
}

字符串

unhi4e5o

unhi4e5o2#

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

字符串
这是一个DEMO

ssm49v7z

ssm49v7z3#

我会使用这样的方法:

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

mf98qq94

mf98qq944#

这是我用来重命名文件的

public static string AppendToFileName(string source, string appendValue)
{
    return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}

字符串

66bbxpm5

66bbxpm55#

或者File.Move方法:

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

字符串
顺便说一句:\是一个相对路径和/一个web路径,请记住这一点。

fslejnso

fslejnso6#

你可以试试这个

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);

字符串

kiayqfof

kiayqfof7#

试试这个

File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");

字符串

相关问题