簡體   English   中英

在 C# 中更改圖像路徑的文件名

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

我的圖片網址是這樣的:

photo\myFolder\image.jpg

我想改變它,使它看起來像這樣:

photo\myFolder\image-resize.jpg

有什么捷徑可以做到嗎?

以下代碼片段更改了文件名並保持路徑和擴展名不變:

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"

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

這是一個演示

或者 File.Move 方法:

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

順便說一句:\\ 是相對路徑和 / 網絡路徑,請記住這一點。

這是我用於文件重命名的

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

我會使用這樣的方法:

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

你可以試試這個

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

試試這個

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