SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have seen code such as:

String fileToUpload = @"C:\YourFile.txt";
    String sharePointSite = "";
    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.

share|improve this question
up vote 3 down vote accepted

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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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