user3283415
user3283415

Reputation: 119

C# rename all files in a folder

I hve a small code which can rename all files (picture) in a folder and it looks like this:

static void Main(string[] args)
    {
        try
        {
            DirectoryInfo d = new DirectoryInfo(@"C:\Users\filip_000\Pictures\Prag");
            int i = 1;

            foreach (var file in d.GetFiles())
            {
                Directory.Move(file.FullName, @"C:\Users\filip_000\Pictures\Prag\" + "Prag_" + i.ToString() + ".jpg");
                i++;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

It works fine, but I would like to rename the pictures (Prag_1, Prag_2, Prag_3...) according to date/time of the file. I mean: the first picture I made on 25.03.2016 16:04 should be "Prag_1" and the last picture I took on 27.03.2016 19:19 should be "Prag_n".

I hope I could explain my issue. Thank you for helping.

Filippo.

Upvotes: 0

Views: 6347

Answers (2)

Siyavash Hamdi
Siyavash Hamdi

Reputation: 3087

OrderBy CreationTime property can be good choice:

foreach (var file in d.GetFiles().OrderBy(f => f.CreationTime))
{
    Directory.Move(file.FullName, @"E:\MP3 #1\Prag\" + "Prag_" + i.ToString() + ".jpg");
    i++;
}

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

Order files on LastWriteTime and then move.

 foreach (var file in  d.GetFiles().OrderBy(f => f.LastWriteTime))
 {
     Directory.Move(file.FullName, @"C:\Users\filip_000\Pictures\Prag\" + "Prag_" + i.ToString() + ".jpg");
     i++;
 }

Upvotes: 5

Related Questions