1

I have 5 images in a folder. The name of the images are:
img1.jpg
img2.jpg
img3.jpg
img4.jpg
img5.jpg

If I delete img3, I want the other images below 3 to move up and be renamed like:
img1.jpg
img2.jpg
img3.jpg
img4.jpg

I can delete specific image from the folder like this:

     int i = 3;
     string imgpath = @"C:\images" + "/" + "img" + i.ToString() + ".jpg";
     File.Delete(imgpath );

But how do I rename the images below img3 ?

Alisha
  • 88
  • 7
  • 3
    Does this answer your question? [Rename a file in C#](https://stackoverflow.com/q/3218910/328193) – David Aug 12 '22 at 12:41
  • You need to delete the file first and then rename the remaining files. – ChrisBD Aug 12 '22 at 12:44
  • I know how to rename a file using File.Move(), but how to rename with that sequence? – Alisha Aug 12 '22 at 12:49
  • 2
    @Alisha: Well, if you want to perform an operation repeatedly in a sequence, that would involve a *loop*. What have you tried and what isn't working as expected? – David Aug 12 '22 at 12:54
  • is the file names enumeration always without any gaps? – Mong Zhu Aug 12 '22 at 13:02
  • @David: Thanks, Used a for loop after finding the total number of files in the directory and within the for loop, added i+1 in source file name in File.Move(). – Alisha Aug 12 '22 at 13:07

1 Answers1

1

As suggested by David, I used a loop as below to fix the issue:

   int filecount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
   int position = 3
    for (int i = position; i < filecount ; i++)
   {
     string filename1= @"C:\images" + "/" + "img" + (i + 1).ToString() + ".jpg";
     string filename2= @"C:\images" + "/" + "img" + (i).ToString() + ".jpg";
     File.Move(filename1, filename2);
   }
Alisha
  • 88
  • 7