I need help adding a file to the document library then setting metadata. I have modified a console app to use a FileUpload control.
The major issue is that the file is not added to the library. Then I cannot set any metadata. I receive the error "The object specified does not belong to a list." at the line SPListItem listItem = file.Item;
It seems that SPFileCollection should be used but I did not find an example of that. I want to stay in the server OM.
When commenting out the last three lines no error but no document either.
If this entire block is bad please help.
This is NOT a sandboxed solution.
private void UploadDocument()
{
if (uplProjectDocument.HasFile)
{
//Instantiate a new site collection object
using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url))
{
SPWeb spWeb = site.OpenWeb();
//Get the list object inside the subsite
SPFolder listFolder = spWeb.Lists["Documents"].RootFolder;
string folderUrl = spWeb.ServerRelativeUrl + listFolder.Url;
string fileUrl = folderUrl + uplProjectDocument.FileName;
// I want the file from the FileUpload control
System.IO.Stream fStream;
byte[] contents = new byte[uplProjectDocument.PostedFile.InputStream.Length];
fStream = uplProjectDocument.PostedFile.InputStream;
fStream.Read(contents, 0, (int) fStream.Length);
fStream.Close();
SPFile file = spWeb.Files.Add(fileUrl, contents, true, "My Check In comment", false);
SPListItem listItem = file.Item;
listItem["Title"] = uplProjectDocument.FileName + "@ " + DateTime.Now.ToString();
listItem.Update();
}
}
}