Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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.
Posted
Updated 3-Nov-17 5:02am

There are a few ways to do this, but the simplest is to use Path.GetFileNameWithoutExtension and Path.GetExtension:
C#
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.
 
Share this answer
 
Comments
1Future 7-Nov-17 3:46am    
Thank you
OriginalGriff 7-Nov-17 3:48am    
You're welcome!
See the Path Class (System.IO)[^].

You can split the path using GetDirectoryName(), GetFileNameWithoutExtension(), and GetExtension() and build the new path from these and appending the count to the file name without extension. Note that GetDirectoryName() returns the directory without the trailing separation character. So you have to add that or use a Combine() method.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900