Solved

rename files in a directory

Posted on 2014-09-16
9
124 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
Technology Partners: 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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone 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

1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

761 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