Wednesday, April 07, 2010

Setting the Content Type of a document programatically

I had occasion to write a workflow that collected some documents and uploaded them to a documnet library. Pretty easy task, however I hit a little snag. Each document had a unique content type depending on the type of document. How would one go about setting the content type of a document that was being added to a doc lib programatically I asked. It would make sense to do it like so:

SPContentType type = list.ContentTypes["[Enter Content Type ID]"];
file.Item.ContentType = type;
folder.Files.Add(file);
folder.Update();
list.Update();

Alas, no. You see file.Item.ContentType is READ ONLY. Hmmm, now what? Well answer was a little more obscure than I expected. But ironically was the same methode I was using for someting else. Here is the solution:

Hashtable fileProps = new Hashtable();
fileProps.Add("ContentType", fileDocType);

Where fileDocType is passed in as a string representing the name of the ContentType. I already had the Hashtable created to set some other metadata on the document, so I really only need one additional line of code. Neat huh?

No comments: