469,575 Members | 1,658 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,575 developers. It's quick & easy.

Renaming files in C# based old file name

Hell All,

I have looked around and not found the solution I am looking for within the old threads. Here is my problem:

I have a directory full of .img and .rrd files that have long filenames that need to be trimmed down because the program I am using to open these files lists them not only by the name, but by how many characters are in the name. Here is an example of a filename and how I want it to look afterward:

454_0254_0583_Rockingham_nc05_MAYODAN_SW_20050624. img


As you can see I only want to keep a couple sets of numbers and the date. Everything else is useless to me. A potential problem is that the names are not consistent in length or how they denote the date at the end.

I'm trying to use C# to do this because I have other programs that need to be built in this language as well. I've read a little and think I know how to read filenames and move files, but I don't have a clue as to the method for renaming the files based on the old filenames.

Thanks for your help!
Apr 27 '07 #1
1 6868
807 Expert 512MB
You use System.IO.File.Move to rename files. Here is an example that does most of what you want. It doesn't do anything fancy to the filename: just keeps the first group, so 2007_12_3_important.img will be renamed to 2007.img. Also, I have using System.IO at the top. Warning -- I think move will wipe out any existing file with the same name, so you will want to do a File.Exists on the new filename. Be sure to test it a lot and backup the files before trying it on real data. I made many mistakes on just these few lines of code. :) Sam
Expand|Select|Wrap|Line Numbers
  1. string[] sFiles = Directory.GetFiles (Environment.GetFolderPath (Environment.SpecialFolder.MyPictures));
  2. foreach (string sOld in sFiles)
  3. {
  4.     FileInfo fi = new FileInfo(sOld);
  5.     if (fi.Extension == ".img")
  6.     {
  7.         string s = fi.Name.Split("_".ToCharArray())[0];
  8.         File.Move(sOld, fi.Directory + "\\" + s + fi.Extension);
  9.     }
  10. }
Apr 27 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by MikeY | last post: by
16 posts views Thread by dudufigueiredo | last post: by
1 post views Thread by Don Leverton | last post: by
1 post views Thread by MikeY | last post: by
1 post views Thread by Chris | last post: by
8 posts views Thread by BillCo | last post: by
1 post views Thread by farseer | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.