I have to use the SPFileCollection.Add Method to add a new item into a document library but no overload of this method seems to fit.
The szenario: If a file is added to a document library and the departments choice field with multi-select (checkboxes) has selected values then the itemUpdated event is supposed to create links to the added file in the selected departments purchasing folder.
What currently happens: The code adds the file as a new file not as a link.
I tried the following...
string departments = Convert.ToString(properties.ListItem[Constants.Departments]);
if (!string.IsNullOrEmpty(departments))
{
string[] linkTargets = departments.Split(';', '#');
string purchasingLink = string.Concat(properties.Web.Url, "/", properties.List.RootFolder.Url, "/", Constants.Purchasing, "/");
foreach (string linkTarget in linkTargets)
{
if (!string.IsNullOrEmpty(linkTarget))
{
SPFolder targetFolder = properties.Web.GetFolder(purchasingLink + linkTarget);
SPFileCollection targetLibFiles = properties.List.RootFolder.Files;
targetLibFiles.Add()
string fileUrl = string.Concat(purchasingLink, linkTarget, "/", properties.ListItem.File.Name);
SPFile newFile = targetLibFiles.Add(fileUrl, properties.ListItem.File.OpenBinary());
SPListItem newItem = newFile.Item;
newItem[SPBuiltInFieldId.ContentType] = SPBuiltInContentTypeId.LinkToDocument;
SPFieldUrlValue linkFieldValue = new SPFieldUrlValue();
linkFieldValue.Url = fileUrl;
newItem[SPBuiltInFieldId.URL] = linkFieldValue;
newItem.Update();
}
}
}
UPDATE: So i checked out the blog post linked by James Michal Lucas in his comment.
I couldnt copy paste it since the overload used in the method does not exist but it had some interesting points like the hashtable to provide the content type in the Add(...) method. The resulting modification in my code:
Hashtable itemProperties = new Hashtable();
SPContentTypeId ctId = SPBuiltInContentTypeId.LinkToDocument;
itemProperties["ContentTypeId"] = ctId.ToString();
string fileUrl = string.Concat(purchasingLink, linkTarget, "/", properties.ListItem.File.Name);
SPFile newFile = targetLibFiles.Add(fileUrl, properties.ListItem.File.OpenBinary(), itemProperties);
Executing this and then checking the content type of the new item with powershell reveals:
PS C:\Users\xy> $file.Item.ContentType.Name
Link to a Document
However deleting the original file does not disable the "link". It still works fine. So its not a link after all.