Renaming image files

I would like to rename a directory (C:\Users\userPC\Desktop\MATT\PROVA\IMG\AW12) that contains 3.000 image files with C#. These images actually have this type of name:

area1_area2_area3_area4.jpg

I would like to take the area2 and area4 to form a new file renamed to area2_area4.jpg. These areas haven't a regular number of character. How can I do? I've found this discussion Rename image files on server directory

But I'm a newbie with programming and I can't work our how to solve my problem.

Upvotes: 0

Views: 6231

Answers (3)

nucandrei
nucandrei

Reputation: 951

Here is a solution.Please be aware that it will not check before making any mess :)

public void rename(String path)
{
  string[] files =System.IO.Directory.GetFiles(path);
  foreach(string s in files)
  {
     string[] ab=s.split('_');
     if(ab.Lenght>3)  
     {
         string newName=ab[1]+ab[3];
         System.IO.File.Move(s,path+newName);
     }
  }
}

You must call the method using this type of parameter

rename("C://Users//userPC//Desktop//MATT//PROVA//IMG//AW12//")

The separator can be changed here ->s.split('_')

Upvotes: 2

Patrik Svensson
Patrik Svensson

Reputation: 13844

using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Rename all files in the C:\Temp\ directory.
            Program.RenameFiles(new DirectoryInfo(@"C:\Temp\"));
        }

        public static void RenameFiles(DirectoryInfo path)
        {
            // Does the path exist?
            if (path.Exists)
            {
                // Get all files in the directory.
                FileInfo[] files = path.GetFiles("*.jpg");
                foreach (FileInfo file in files)
                {
                    // Split the filename
                    string[] parts = file.Name.Split('_');
                    // Concatinate the second and fourth part.
                    string newFilename = string.Concat(parts[1], "_", parts[3]);
                    // Combine the original path with the new filename.
                    string newPath = Path.Combine(path.FullName, newFilename);
                    // Move the file.
                    File.Move(file.FullName, newPath);
                }
            }
        }
    }
}

Upvotes: 1

Andre Lombaard
Andre Lombaard

Reputation: 7105

First get a list of file names contained in the folder with

var listOfFileNames = Directory.GetFiles(directory);

You mentioned that the areas do not have a regular number of characters (I assume that the areas are separated by the underscore character). So split each file name into it's four areas, using the underscore character as a separator.

Then build your new file name, for exmple,

foreach(var fileName in listOfFileNames)
{
    var areas = fileName.Split('_');
    var newFileName = string.Format({0}{1}{2}, areas[0], areas[1],".jpg");
}

Hope this helps

Upvotes: 0

Related Questions