Create Media Folders programmatically

Vote:
 

Hi - I'm in the process of migrating an image importer from Epi 6R2 to Epi 7.5 and while I can successfully import images, I'm unable to programatically create new folders to put the images in.

I'd like to create a folder stucture similar to the following:

Photos\Events\Event1\photo1.jpg

Photos\Events\Event1\photo2.jpg

Photos\Events\Event2\photo1.jpg

Photos\Events\Event2\photo2.jpg

The code I use to save the images is as follows:

public void SaveFile(string path, string fileName, byte[] bytes)
{
var contentRepository = ServiceLocator.Current.GetInstance();
var blobFactory = ServiceLocator.Current.GetInstance();

var imageFile = contentRepository.GetDefault(SiteDefinition.Current.GlobalAssetsRoot);
imageFile.Name = fileName;

var blob = blobFactory.CreateBlob(imageFile.BinaryDataContainer, ".jpg");

Stream stream = new MemoryStream(bytes);
blob.Write(stream);

imageFile.BinaryData = blob;
var file1ID = contentRepository.Save(imageFile, SaveAction.Publish, AccessLevel.NoAccess);
}


Thanks,

Jon

#120453
Apr 17, 2015 12:37
Vote:
 

Hi,

To create a folder, you can use ContentFolder instead of ImageFile 

Regards.

/Q

#120455
Apr 17, 2015 13:03
Vote:
 

To create a folder you should use ContentFolder as  the type argument to GetDefault<T> as 

contentRepository.GetDefault<ContentFolder>(parentLink)
#120456
Apr 17, 2015 13:04
Vote:
 

Thanks both, that works perfectly!

To anyone in the same boat I've thrown some rough code which will create a folder in the root if a parent content reference isn't passed and in a sub folder if it is.

        //Create a Folder in the root
        public ContentReference CreateFolder(string folderName)
        {
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
            var contentFile = contentRepository.GetDefault<ContentFolder>(SiteDefinition.Current.GlobalAssetsRoot);
            contentFile.Name = folderName;
            return contentRepository.Save(contentFile, SaveAction.Publish, AccessLevel.NoAccess);
        }

        //Create a new folder
        public ContentReference CreateFolder(string folderName, ContentReference parentReference)
        {
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
            var contentFile = contentRepository.GetDefault<ContentFolder>(parentReference);
            contentFile.Name = folderName;
            return contentRepository.Save(contentFile, SaveAction.Publish, AccessLevel.NoAccess);
        }

- Jon

#120459
Apr 17, 2015 13:36
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.