I have two libraries, one with forms(xml) and one with a custom document content type.
I have an event receiver ItemUpdated on the form library, which interprets the added/modified form, and creates a Document based on this data, by using the DocumentFormat.OpenXml.WordprocessingDocument sdk.
Sidenote: ItemUpdated fires twice (by design it seems). I can not for the life of me get it to fire one time only, if someone could help me with this too, that would be great.
After the package is created, I write it to a MemoryStream, and uses the ToArray() method to create a byte[] array.
Finally, I add the file/byte[] to my library.
Now all this works, and the file is, in fact, added to the library, but I get an exception the second time it runs on this line:
list.RootFolder.Files.Add("filename.docx", bytes, properties, true);
Microsoft.SharePoint.SPException was caught Message=Cannot open file "http://path/filename.docx".
My (stripped) code looks like this:
var generator = new WordDocumentGenerator();
var bytes = generator.CreatePackage();
list.RootFolder.Files.Add("fileName.docx", bytes, properties, true);
The CreatePackage method looks like this:
public byte[] CreatePackage()
{
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
using (var package = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
{
CreateParts(package); //Adds parts to the document, no IO
}
bytes = stream.ToArray();
}
return bytes;
}
Since it works, I'm contemplating just ignoring this error, but naturally that's not really what I want to do.