如何在C#中重命名/追加文件名? [英] How do I rename/append a filename in C#?
问题描述
大家好,
对于一些人来说这可能很简单但是我在努力实现这个目标。
我有像这样的图像列表:
var renamedFiles = new List< ImageModel>();
var list = new 列表<> {' image1.jpg',' Image2.jpg',image3.jpg};
int fileCount = 0 ;
foreach ( var image in list)
{
fileCount ++;
// 我想用文件计数附加每个文件名;
// 所以我想使用filecount重命名为image1.jpg。
// 例如:image1.jpg将重命名为image1_1.jpg
// 所以为了达到这个目的,我需要做类似的事情:image1_+ fileCount + .jpg
renamedFiles.Add(image)
}
任何帮助都将不胜感激。
我尝试了什么:
我想我需要拆分文件名并在其间插入计数文件名和jpg,但我不确定如何做到这一点。
有几种方法可以做到这一点,但最简单的方法是使用Path。 GetFileN ameWithoutExtension和Path.GetExtension:
string filename = image1.jpg;
int fileCount = 1 ;
string renameTo = string .Format( {0} _ {1} {2},Path.GetFileNameWithoutExtension(filename),
fileCount,
Path.GetExtension (文件名));
请注意,如果图像包含路径,则还需要将其添加到文件中。
< blockquote>请参阅路径类(System.IO) [ ^ ]。
您可以使用 GetDirectoryName()
拆分路径, GetFileNameWithoutExtension()
和 GetExtension()
并从这些路径构建新路径并将计数附加到文件名而不带扩展名。请注意 GetDirectoryName()
返回没有尾随分隔符的目录。所以你必须添加它或使用 Combine()
方法。
Hi All,
This may be quite simple for some but i'm struggling on how to achieve this.
I have a list of images like so:
var renamedFiles = new List<ImageModel>();
var list = new List<> {'image1.jpg', 'Image2.jpg', image3.jpg};
int fileCount = 0;
foreach(var image in list)
{
fileCount++;
//I want to append each file name with the file count number;
//so i would like to rename for example "image1.jpg" using the filecount.
// for example : "image1.jpg" to be renamed to "image1_1.jpg"
//so in order to achieve this i need to do something like: image1 "_" +fileCount+ .jpg
renamedFiles.Add(image)
}
Any help would be appreciated.
What I have tried:
I think i need to split the file name and insert the count in between the file name and the jpg but i', unsure on how to do this.
There are a few ways to do this, but the simplest is to use Path.GetFileNameWithoutExtension and Path.GetExtension:
string filename = "image1.jpg"; int fileCount = 1; string renameTo = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(filename), fileCount, Path.GetExtension(filename));
Do note that if you images include a path, you will need to add that to the file as well.
See the Path Class (System.IO)[^].
You can split the path usingGetDirectoryName()
,GetFileNameWithoutExtension()
, andGetExtension()
and build the new path from these and appending the count to the file name without extension. Note thatGetDirectoryName()
returns the directory without the trailing separation character. So you have to add that or use aCombine()
method.
这篇关于如何在C#中重命名/追加文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!