Solved

rename files in a directory

Posted on 2014-09-16
9
125 Views
Last Modified: 2014-09-17
Hello,
I need some code for renaming files within a folder to be the path of 3 levels.
Here is an example of what I am describing.

Photos
      Cars
             Sport
                      Ford
                      File001.jpg ...........  would be renamed to Cars_Sport_Ford_File001.jpg
                      File002.jpg ...........  would be renamed to Cars_Sport_Ford_File002.jpg
              Volvo
                      File001.jpg ...........  would be renamed to Cars_Sport_Volvo_File001.jpg
                      File002.jpg ...........  would be renamed to Cars_Sport_Volvo_File002.jpg

The files level will always be 3 below the parent

Thanks in Advance!
0
Comment
Question by:H-SC
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 3
9 Comments
 
LVL 9

Accepted Solution

by:
dustock earned 250 total points
ID: 40326088
Give this code a shot.  You may have to modify the numbers in the split() depending on your directory.  In my case I used "c:\temp\test" and then found the directories from there.  So if you have something longer than c:\temp\test you will have to add a number for each additional "\".
example "c:\temp\test\EE_test" would require the name to start with split(4)

Let me know if you have any questions.

    Private Sub RenameFiles()
        Dim strStartPath As String = "c:\temp\test"
        Dim split As String()

        Dim Dirs() As String = Directory.GetDirectories(strStartPath)

        For Each Dir As String In Dirs
            Dim TypeDirs() As String = Directory.GetDirectories(Dir)

            For Each TypeDir As String In TypeDirs
                Dim MakeDirs() As String = Directory.GetDirectories(TypeDir)

                For Each MakeDir As String In MakeDirs
                    Dim Files() As String = Directory.GetFiles(MakeDir)

                    For Each photo As String In Files
                        split = photo.Split("\")
                        Try
                            My.Computer.FileSystem.RenameFile(photo, String.Format("{0}_{1}_{2}_{3}", split(3), split(4), split(5), Path.GetFileName(photo)))
                        Catch ex As Exception

                        End Try
                    Next
                Next
            Next
        Next
    End Sub

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40326125
The above is mostly correct.  

This takes into account the fact that you're looking for some root, and will only take the directories after that point.

A combination of the 2 will give you what you're after.

     DirectoryInfo inf = new DirectoryInfo(@"C:\SomeDIr\SomeDir2\Photos\Cars\Sports\Ford\");
            List<string> dirs = inf.FullName.Split('\\').ToList();
            string root = "Photos"; // case sensitive . . . use tolower() in the compare below to ignore.

            bool dirFound = false;
            foreach (string dir in dirs)
            {
                if (dir == root)
                {
                     //found target dir, now get the directories as the "root" of the file name.
                    dirFound = true;
                    root = "";
                    continue;
                }

                if (dirFound)
                  root += dir + "_";
            }

//now rename the files in the directory using root + filename.

Open in new window

0
 
LVL 1

Author Comment

by:H-SC
ID: 40326521
dustock,
This works great, however is there a way that the directory with the files that get renamed do not get renamed again.  I have this code attached to an event that can be initiated multiple times.  I tried the code and if I click on the button where the code is attached it keeps adding the string to the file name I think that I need a flag or file created on the first go that it will look for afterwards.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:H-SC
ID: 40326526
Kyle,
For some reason I can't get that code to work correctly.
0
 
LVL 9

Expert Comment

by:dustock
ID: 40326594
you could throw an if block in...maybe something like

If Not Path.GetFileName(photo).ToLower.StartsWith(String.Format("{0}_{1}_{2}", split(3), split(4), split(5)).ToLower) Then
                            Try
                                My.Computer.FileSystem.RenameFile(photo, String.Format("{0}_{1}_{2}_{3}", split(3), split(4), split(5), Path.GetFileName(photo)))
                            Catch ex As Exception

                            End Try
                        End If

Open in new window


Also, Kyle's code is in C#, so that may be why you are having issues with it
0
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 250 total points
ID: 40326752
My apologies . . . here's the code in VB.Net

Dim inf As New DirectoryInfo("C:\SomeDIr\SomeDir2\Photos\Cars\Sports\Ford\")
Dim dirs As List(Of String) = inf.FullName.Split("\"C).ToList()

' case sensitive . . . use tolower() in the compare below to ignore.
Dim root As String = "Photos"  

Dim dirFound As Boolean = False

For Each dir As String In dirs
	If dir = root Then
		'found target dir, now get the directories as the "root" of the file name.
		dirFound = True
		root = ""
		Continue For
	End If

	If dirFound Then
		root += dir & "_"
	End If
Next

'now rename the files in the directory using root + filename.

Open in new window

0
 
LVL 1

Author Comment

by:H-SC
ID: 40328100
Perfect!
dustock and Kyle do you mind if I split the points?
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40328137
I'm fine with it.  Will let Dustock chime in as well :-).
0
 
LVL 9

Expert Comment

by:dustock
ID: 40328196
That's fine
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to extract certain lines from textfile and save them to another file? 6 47
Access Schema 6 53
Copying from a network share 3 36
Run software updates from the website 6 49
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question