Renaming files in a directory

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am a novice in C# and need help. I want to write a simple program to read
a bunch of files from a specified directory and rename those files in a
sequential fashion., changing a bunch of image file names.

For example, changing:
a011.jpg
a 011.1.jpg
i234.jpg

to

img001.jpg
img002.jpg
img003.jpg

There are some 600 files, so doing it manually would be a pain. I don't know
my C# or .NET framwork well enough yet to do this by myself quickly. I
think I should be able to do it with a simple console program. I am hoping
somebody could help me.
 
Well, the way I would do it is that I would get all the files in the
directory using the GetFiles method on the DirectoryInfo instance which
represents the directory. At this point, you can sort the files according
to your criteria (if not, use the GetFiles method on the Directory class,
since it should be faster, since it only returns names of the files, and not
file info classes).

Once you have that, you can cycle through the array, and call the static
Move method on the File class to rename the file.

Hope this helps.
 
I am a novice in C# and need help. I want to write a simple program to read
a bunch of files from a specified directory and rename those files in a
sequential fashion., changing a bunch of image file names.

For example, changing:
a011.jpg
a 011.1.jpg
i234.jpg

to

img001.jpg
img002.jpg
img003.jpg

There are some 600 files, so doing it manually would be a pain. I don't know
my C# or .NET framwork well enough yet to do this by myself quickly. I
think I should be able to do it with a simple console program. I am hoping
somebody could help me.

Sure - look at Directory.GetFiles and File.Move.
 
Thanks for you help. This is what I came up with:
using System;

using System.IO;



namespace FileRename

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

//

// TODO: Add code to start application here

//

try

{

DirectoryInfo di = new DirectoryInfo(@"G:\Pictures\Target");

// Get a reference to each file in that directory.

FileInfo[] fiArr = di.GetFiles("*.jpg");

// Define an Integer Counter

int i = 0;

string path;

// Display the names of the files.

foreach (FileInfo fri in fiArr)

{

//Console.WriteLine(fri.Name);

//Change the prefix to something that is not already there

path = @"G:\Pictures\Target\" + "pic" + i.ToString("D3")+".jpg";

fri.MoveTo(path);

i++;

}


Console.WriteLine("Done");

}


catch (Exception e)

{

Console.WriteLine("The process failed: {0}", e.ToString());

}

}

}

}

This is actually slightly modified from what I ran, but if follows the
guidance I got. I got my pictures sorted and renamed.
 
Back
Top