I have a bunch of files (mostly pdf and docx files) on the harddrive that I want to add to my EPiServer 8 site programmatically. I'm having some troubles. Here is what I've tried:
var contentRepository = ServiceLocator.Current.GetInstance();
var blobFactory = ServiceLocator.Current.GetInstance();
var file1 = contentRepository.GetDefault(SiteDefinition.Current.GlobalAssetsRoot);
var container = file1.BinaryDataContainer;
var blob = blobFactory.CreateBlob(container, ".docx");
using (var fs = new FileStream("c:\\test.docx", FileMode.Open))
file1.BinaryData = blob;
file1.Name = "test.docx";
var file1ID = contentRepository.Save(file1, SaveAction.Publish);
A file called "test.docx" is created/added to Episerver but it only contains jibberish and not the actual content from the existing file. What am I doing wrong here?
Can you try to use IContentTypeRepository & MediaDataResolver:
var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var mediaDataResolver = ServiceLocator.Current.GetInstance<ContentMediaResolver>();
var mediaType = mediaDataResolver.GetFirstMatching(".jpg");var contentType = contentTypeRepository.Load(mediaType);
Just by reading your code it looks like it should work. Does it make any difference if you add the FileAccess.Read and FileShare.Read parameters when you create the FileStream instance?
using (Stream fs = new FileStream("C:\\test.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
I would replace the last line in Quan's code with:
var file1 = contentRepository.GetDefault<IContentMedia>(SiteDefinition.Current.GlobalAssetsRoot, contentType.ID);
Thank you for the answers. I have tried all your suggestions but no difference in the result.
The thing is that it works fine if I try with an existing textfile instead, but as soon as I work with something more advanced (docx) It doesn't work so good (See screenshot. Ignore the license message, I haven't downloaded a dev license yet :))
So I suppose I have to do something special with more advanced file types?
EDIT: I got an epiphany now. Maybe it has to do with the missing license. Since that is appending to the content the file might get corrupt?
I would download a dev license and try it again. It's probably caused by the license exception being injected.
UPDATE: I just noticed you realized it all by yourself. :)
Yes - that is it. The reason was when you download the file - docx, our license system injects the warning in to the response - which is supposed to be an HTML response.
Placing a license should solve your problem. It should always be advised to develop with working license - no hidden headache :)
Have a nice day.
Thanks for your time guys. Sometimes you just need to ask the questions to realize what the answer is :) It now works with the license. I should stop being lazy.. ;)