0

I have this below code which is copying files from one folder and creating a new folder if does not exist and then pasting the files over there.I am getting a path not found error..meaning if I want to create a new folder in c:\versions\myfolder it is not creating the path and throwing error..am I doing something wrong here.

Dim LastMonth
Dim strFolder 
Const  strFile = "C:\inetpub\wwwroot\Shared"
Const Overwrite = True
Dim oFSO

LastMonth = DateAdd("m",-1,Date)

strFolder = "C:\Versions\" & "Common_" & Replace(LastMonth,"/","-")&"/"
Set oFSO = CreateObject("Scripting.FileSystemObject")

WScript.Echo strFolder
If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFolder strFile, strFolder, Overwrite

To make the question easy to understand I also tried doing this oFSO.CreateFolder("C:\Versions\Shared") but it doe snot work.

user505210
  • 1,362
  • 11
  • 28
  • 50
  • Got the answer from this blog http://www.robvanderwoude.com/vbstech_folders_md.php ..basically u cannot create more than one hierarchy deep folders directly – user505210 Jun 18 '13 at 16:55

2 Answers2

3

You can create folders including their parent folders by recursively traversing the path upwards until you find an existing parent folder, and then create the child folders as you descend back:

Set fso = CreateObject("Scripting.FileSystemObject")

Sub CreateSubFolder(path)
  If Not fso.FolderExists(path) Then
    drive = fso.GetDriveName(path)
    If Not fso.DriveExists(drive) Then
      WScript.Echo "Drive " & drive & " doesn't exist."
      WScript.Quit 1
    End If
    parent = fso.GetParentFolderName(path)
    If Not fso.FolderExists(parent) Then CreateSubFolder parent
    fso.CreateFolder path
  End If
End Sub

CreateSubFolder "C:\path\to\some\distant\sub\folder"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
1
  • You can't create a folder and subfolder at the same time, the parent folder must exists before you can create the sub-folder.
  • You put a forward slash (/) in the folder name instead of a backslash (\) in the strFolder path. (Typo?!)

Hope that helps

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Aron Einhorn
  • 379
  • 3
  • 10
  • +1 for noticing the trailing forward slash, although it doesn't prevent folder creation. The `FileSystemObject` treats forward and backward slashes alike. – Ansgar Wiechers Jun 18 '13 at 21:54