Create mutiple folders from mutiple filenames

artwork21

New member
Joined
Dec 14, 2010
Messages
4
Programming Experience
Beginner
The code below creates multiple folders based on different file names and moves those files into the new folders. For example, files ABC and XYZ are moved into a newly created folder named ABC and XYZ. I want to advance the code to allow slightly different file names to go into a common folder. Example, I want file ABC_rock, ABC_soil, and ABC_water to be put into a folder named ABC still, AND file XYZ_rock, XYZ_soil, and XYZ_water to be put into a folder named XYZ. I do not want a separate folder created for ABC_rock, ABC_soil, and ABC_water. Any suggestions are greatly appreciated. Thank you for your help.
VB.NET:
 Dim strOutputLocation As String = "C:\Temp"
        Dim rootPath As String = strOutputLocation
        
        For Each filepath As String In IO.Directory.GetFiles(rootPath)

            Dim folderName As String = IO.Path.GetFileNameWithoutExtension(filepath)
            Dim folderPath As String = IO.Path.Combine(rootPath, folderName)

            If Not IO.Directory.Exists(folderPath) Then
                IO.Directory.CreateDirectory(folderPath)
            End If

            Dim fileName2 As String = IO.Path.GetFileName(filepath)
            Dim newFilePath As String = IO.Path.Combine(folderPath, fileName2)

            File.Move(filepath, newFilePath)

        Next
 
Try something like this:

VB.NET:
Dim rootPath As String = "C:\Temp"
For Each filepath As String In IO.Directory.GetFiles(rootPath)
   Dim folderName As String = IO.Path.GetFileNameWithoutExtension(filepath).Split("_").GetValue(0)
   Dim folderPath As String = IO.Path.Combine(rootPath, folderName)
   If Not IO.Directory.Exists(folderPath) Then
      IO.Directory.CreateDirectory(folderPath)
   End If
   Dim fileName2 As String = IO.Path.GetFileName(filepath)
   Dim newFilePath As String = IO.Path.Combine(folderPath, fileName2)
   File.Move(filepath, newFilePath)
Next

Hope this helps
-Josh
 
Glad to help!
 
Back
Top