0

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?

1

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
    }
}
| improve this answer | |
1

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.

| improve this answer | |
  • 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? – user3299197 Apr 23 '14 at 20:53
  • yup. SPList list = subsite.lists['library title / url'] – Sudhir Kesharwani Apr 23 '14 at 20:54
  • 1
    Refer to msdn.microsoft.com/en-us/library/… for a list of constructors on the SPList class – Sudhir Kesharwani Apr 23 '14 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? – user3299197 Apr 23 '14 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. – Paiman Samadian May 1 '14 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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