I am having major woes trying to add a file to the document library. 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. 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);

                SPFile file = spWeb.Files.Add(fileUrl, contents, true, "My Check In comment", false);

                SPListItem listItem = file.Item;
                listItem["Title"] = uplProjectDocument.FileName + "@ " + DateTime.Now.ToString();

1 Answer 1


You have written incorrect code.

1) spWeb.Files.Add

2) use using block for SPWeb in above case.

Please go through it you will be able to resolve the issue.

using (SPSite site = newSPSite("url"))

using (SPWeb web = site.OpenWeb())


SPDocumentLibrary documentLib = web.Lists["YourLibraryName"] as SPDocumentLibrary;

Stream fStream = FileUpload1.PostedFile.InputStream;
byte[]  _byteArray = new byte[fStream.Length];
fStream.Read(_byteArray, 0, (int)fStream.Length);

web.AllowUnsafeUpdates = true;

string _fileUrl = documentLib.RootFolder.Url + "/" + FileUpload1.PostedFile.FileName;

bool IsOverwriteFile = true;
SPFile file = documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile);

SPListItem item = file.Item;
item["Title"] = FileUpload1.PostedFile.FileName;

web.AllowUnsafeUpdates = false;


  • This was a concise answer and I have resolved the issue. Thanks. For the lurkers: be sure to use a Path.GetFileName on PostedFile.FileName. Commented Sep 23, 2013 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.