I am using the Core Service on Tridion 2011. I want to create a folder structure, and then create a component in that structure.
Example: Path of folder structure: /ABCD/DEFG/aaaaa
If the folder exists, we need not create folder. If it doesn't exist we have to create it and create component in it.
I know how to create the component in a folder having URI.
The following is the code I use when I need to Get or Create Folders with SDL Tridion's CoreService. It's a simple recursive method that checks for the existence of the current folder. If it doesn't exist, it goes into GetOrCreate the parent folder and so on until it finds an existing path. On the way out of the recursion, it simply creates the new Folders relative to their immediate parent.
Note: this method does not check the input folderPath
. Rather, it assumes it represents a valid path.
private FolderData GetOrCreateFolder(string folderPath, SessionAwareCoreServiceClient client)
{
ReadOptions readOptions = new ReadOptions();
if (client.IsExistingObject(folderPath))
{
return client.Read(folderPath, readOptions) as FolderData;
}
else
{
int lastSlashIdx = folderPath.LastIndexOf("/");
string newFolder = folderPath.Substring(lastSlashIdx + 1);
string parentFolder = folderPath.Substring(0, lastSlashIdx);
FolderData parentFolderData = GetOrCreateFolder(parentFolder, client);
FolderData newFolderData = client.GetDefaultData(ItemType.Folder, parentFolderData.Id) as FolderData;
newFolderData.Title = newFolder;
return client.Save(newFolderData, readOptions) as FolderData;
}
}
I would use IsExistingObject - passing in the WebDAV URL - to see if the Folder already exists. If it returns false, you can go ahead and create the folder.
Edit: Here's some quick pseudo code...
string parentFolderId = @"/webdav/MyPublication/Building%20Blocks";
var client = GetCoreServiceClient();
if (!client.IsExistingObject(parentFolderId + "/AAA"))
{
var folder = client.GetDefaultData(2, parentFolderId);
folder.Title = "AAA";
client.Save(folder);
// Create the other folders and components here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With