0
votes

I'm trying to create a new document in a SharePoint (WSS 3.0) document library with a specific content type. But the new document always has the default content type for the doc lib, not the custom one I specified :-(

I'm using SPFileCollection.Add to create the file, and using the properties Hashtable to pass the content type ID/name:

SPList list = web.Lists["Test Doc Lib"];

Hashtable properties = new Hashtable();
properties.Add("ContentType", "MyCustomContentType");
properties.Add("ContentTypeId", list.ContentTypes["MyCustomContentType"].Id.ToString());

list.RootFolder.Files.Add("Test File.html", Encoding.UTF8.GetBytes("test"), properties);

All the sample code I can find uses SPFileCollection.Add to initially create the file, then re-fetches the new SPListItem and sets the content type on this. I don't want to do this because it would cause both ItemAdding and ItemUpdating events to fire.

2

2 Answers

1
votes

This works for me.

SPContentTypeId id=list.ParentWeb.AvailableContentTypes["ContentTypeName"].Id;
Hashtable htMetaData = new Hashtable();
htMetaData.Add("ContentTypeId", id.ToString());
SPFile newfile = docSetFolder.Files.Add(fullFileUrl,fileByteArray,htMetaData,true);
0
votes

I have never tried to add file in your way, but IMHO you can create file and then change list item content type. You can disable event firing to prevent ItemAdding & ItemUpdating events from firing. There're many articles about this (search for "sharepoint disable event firing"). Some links:

http://blogs.syrinx.com/blogs/sharepoint/archive/2008/11/10/disabling-event-firing-on-splistitem-update-differently.aspx

http://anylookup.com/how-to-really-disable-event-firing-in-sharepoint