programmatically setting content type

So, you have a SharePoint document library. And you are loading content into it programmatically. But you want your content to be a custom content type, right?

Online, something like the following was suggested:

SPContentType theType = theList.ContentTypes["Custom content type"];
SPFile newFile = PublishingWeb.Files.Add(url, stream, true);
newFile.Item["ContentTypeId"] = theType.Id;
theFile.Update();

But with a document, this doesn’t seem to work (and many people had posted comments about it not working for documents). The content type remains “Document”. What to do? I banged my head for a little while before finding this:

Hashtable hash = new Hashtable();
SPContentType theType = theList.ContentTypes["Custom content type"];
if (type != null)
{
hash.Add("ContentType","Custom content type");
}
SPFile newFile = PublishingWeb.Files.Add(url, stream, hash, true);

Now, changing the content type on an existing document is something else entirely. (You could always download the content and reupload, this time passing the content type in the Hashtable… but that seems like a rather unsaavy way to do it.)

Advertisements

About George

I'm interested in theology, languages, translation and various sorts of fermentation.
This entry was posted in Code Samples and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s