简体   繁体   English

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

[英]Change file name of image path in C#

My image URL is like this:我的图片网址是这样的:

photo\myFolder\image.jpg

I want to change it so it looks like this:我想改变它,使它看起来像这样:

photo\myFolder\image-resize.jpg

Is there any short way to do it?有什么捷径可以做到吗?

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"

You can use Path.GetFileNameWithoutExtension method.您可以使用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 .这是一个演示

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.顺便说一句:\\ 是相对路径和 / 网络路径,请记住这一点。

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM