rename files in a directory

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!
LVL 1
H-SCAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dustockCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kyle AbrahamsSenior .Net DeveloperCommented:
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
H-SCAuthor Commented:
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

H-SCAuthor Commented:
Kyle,
For some reason I can't get that code to work correctly.
0
dustockCommented:
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
Kyle AbrahamsSenior .Net DeveloperCommented:
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
H-SCAuthor Commented:
Perfect!
dustock and Kyle do you mind if I split the points?
0
Kyle AbrahamsSenior .Net DeveloperCommented:
I'm fine with it.  Will let Dustock chime in as well :-).
0
dustockCommented:
That's fine
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.