Thursday, October 8, 2009

Creating recursive folders in the Sharepoint Document Library

Microsoft has a sample on how to create folder to place the file. But when I wish to create the recursive sub folders it is not exactly working. Thus I ended up recoding a little to get this task done.

Dim SubFolders As String = "/" + Format(runDate, "yyyy") + "/" + Format(runDate, "MMM").ToUpper()

Dim Site As SPWeb = New SPSite(SPSite).OpenWeb

For Each Folder In SubFolders.Split("/"c)
If Folder <> "" Then
SPFolder += "/" & Folder
EnsureParentFolder(Site, SPSite + SPFolder + "/")
End If
Next Folder
Public Sub EnsureParentFolder(ByVal ParentSite As SPWeb, ByVal Destination As String)
Destination = ParentSite.GetFile(Destination).Url
Dim index As Integer = Destination.LastIndexOf("/")
Try
If index > -1 Then
Dim currentFolder As SPFolder = ParentSite.RootFolder
currentFolder = currentFolder.SubFolders.Add(Destination)
End If
Catch e As Exception
Console.WriteLine(e.Message.ToString)
End Try
End Sub