I would like to use C# to add a file to a library in a subsite.

I believe SPWeb will only reference the site I am on. In an ItemAdded eventreceiver, I want to use something like

SPFolder myLibrary = web.Folders[myURL]; //this does not work. just an example SPFile newfile = myLibrary.Files.Add(fileName, Stream, true);

but on a subsite (Event Receiver is at the top level). I have a string with a destination URL such as "mysite.com/subsite/some%20library/file.docx." Within the ER, can I open the web and and library to add the item there or do I need to split the string to get the subsite and library names each time?

  • Are you trying to route documents by any chance? Commented Apr 24, 2014 at 5:26
  • Yes I am. From the top of the sitecollection to any specified subsite based on the url that my users are entering. Commented Apr 24, 2014 at 13:42
  • Might be a good idea to take a look at the Content Organiser (2010 and 2013) functionality - office.microsoft.com/en-001/sharepoint-server-help/… Commented Apr 24, 2014 at 14:20

2 Answers 2


You can use OpenWeb for defining the web. In case if I have understood your question correctly, something like the below code can be appropriate for you.

using (SPSite site = new SPSite("http://site/subsite"))
// RootWeb returns the http://site and OpenWeb() returns subsite
    using (SPWeb web = site.OpenWeb())
       // Operations to be performed can come in here

When you get an SPWeb object you will be able to get reference to the library, but for that you need to know the name of the library.

So a better to get the Site and LIbrary details from the url, I dont think we have a way of getting library reference using the URL.

  • So the key is to trim the url to only the subsite level to use something like the following: SPSite subSite = new SPSite(trimmedURL) and then try to get the library some other way? Commented Apr 23, 2014 at 20:53
  • yup. SPList list = subsite.lists['library title / url'] Commented Apr 23, 2014 at 20:54
  • 1
    Refer to msdn.microsoft.com/en-us/library/… for a list of constructors on the SPList class Commented Apr 23, 2014 at 20:55
  • Great! Thanks. Do have a follow up question if you don't mind: the "by "url" in that last block, would I be able to enter the whole url as shown in the destination URL example above or would it need to be a shortened version? Commented Apr 23, 2014 at 21:14
  • 1
    I know it is late but you could use SPWeb.Files.Add() method and add your file directly to the library using the full url without bothering retrieving the library object itself. Commented May 1, 2014 at 4:36

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.