I have seen code such as:

String fileToUpload = @"C:\YourFile.txt";
    String sharePointSite = "http://yoursite.com/sites/Research/";
    String documentLibraryName = "Shared Documents";

    using (SPSite oSite = new SPSite(sharePointSite))
        using (SPWeb oWeb = oSite.OpenWeb())
            if (!System.IO.File.Exists(fileToUpload))
                throw new FileNotFoundException("File not found.", fileToUpload);                    

            SPFolder myLibrary = oWeb.Folders[documentLibraryName];

            // Prepare to upload
            Boolean replaceExistingFiles = true;
            String fileName = System.IO.Path.GetFileName(fileToUpload);
            FileStream fileStream = File.OpenRead(fileToUpload);

            // Upload document
            SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

            // Commit 

That lets you upload a file to a library, but it requires a file path. I only have an XDocument and even with the SetBaseURI enabled, it won't work since the XDocument is being passed to a different computer that does not have the same file on it. Any ideas on how to get an XDocument uploaded to a library? It looks like I just need to convert the XDocument to a filestream.

1 Answer 1


SPFileCollection.Add operates with a Stream object. It is not obligatory a FileStream object. It could be a MemoryStream as well. And definitely, you can pass an XDocument object to a memory stream (through XmlWriter).

So, you will need something like the following code fragment:

    public void UploadXDocumentToDocLib(
        XDocument document,
        string fileName,
        string siteUrl,
        string documentLibraryName,
        bool replaceExistingFile)

        using (SPSite site = new SPSite(siteUrl))
            using (SPWeb web = site.OpenWeb())
                var stream = new MemoryStream();
                var writer = XmlWriter.Create(stream);

                // get folder by url
                var folder = web.GetFolder(documentLibraryName);
                // create the file
                folder.Files.Add(fileName, stream, replaceExistingFile);

There were some other inessential problems with your code:

  • You don't need to update folder object when adding a file
  • Better way to retrieve the folder is to use SPWeb.GetFolder method, because SPWeb.Folders could fetch only root folders of the site, not their subfolders

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.