Solved

rename files in a directory

Posted on 2014-09-16
9
120 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 39

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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 39

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 39

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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

758 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

20 Experts available now in Live!

Get 1:1 Help Now