Solved

rename files in a directory

Posted on 2014-09-16
9
121 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
  • 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
 
LVL 1

Author Comment

by:H-SC
ID: 40326526
Kyle,
For some reason I can't get that code to work correctly.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

932 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now