The recommendation is to use EPiServer.Core.ContentAssetHelper (available in IOC container) to manage assetfolders (for example in your code above does not handle the case that folder might already exist).
In your case you could call the method GetOrCreateAssetFolder (which will give you the asset folder if it already exist otherwise it is created for you)
I have fixed the code so that it uses ContentAssetHelper to create the ContentAssetFolder. My question was rather how to get rid of the existing blocks and ContentAssetFolders created by the old code. I noticed even that the moving the page to the waste basket and emptying it won't help - both ContentAssetFolder and the blocks are left intact...
You need to update the "owning content" as well so it points to your new created asset folder. Something like:
var content = contentAssetHelper.GetAssetOwner(assetFolder.ContentLink).CreateWritableClone(); assetFolder.Attach(content); _contentRepository.Save(content, SaveAction.Patch, AccessLevel.NoAccess);
Note however that the above code just updates the content to point to your created assetfolder, it will not take care of deleting the old one.
I have a code which creates blocks programmatically and those are stored in ContentAssetFolder for a page. The ContentAssetFolder is created programmatically like this:
I noticed that ContentAssetFolder is not shown in the tree on Blocks panel when I open the respective page in CMS and I wonder if there is any way to move the blocks to waste basket in CMS. Or do I have to do it programmatically?