views:

36

answers:

2

I'm having an issue with accessing objects within two different instances of the SPSite object if the URL to the site collection is located within two different sites (e.g., http://mysite/Docs1/ and http://mysite/subsite/Docs2/). Consider the following code:

public static void MoveDocument(Uri sourceUrl, Uri destinationUrl)
{
    string sUrl = sourceUrl.ToString();
    string dUrl = destinationUrl.ToString();

    using (SPSite sourceSite = new SPSite(sUrl))
    using (SPSite destinationSite = new SPSite(sUrl))
    {
        SPWeb sourceWeb = sourceSite.OpenWeb();
        SPWeb destinationWeb = destinationSite.OpenWeb();
        SPFile sourceFile = sourceWeb.GetFile(sUrl);
        SPFolder destinationFolder = destinationWeb.GetFolder(dUrl);

        MoveDocument(sourceFile.ParentFolder, destinationFolder, sourceFile.Name);
    }
}

In the code above, if I attempt to initialize an SPFolder that is in a different site than the source website, it fails because SharePoint attempts to look within the same site as sourceSite rather than destinationSite.

The intent is to be able to provide the ability to move a file from one document library to another (whether in the same site collection or not).

What am I doing wrong?

+3  A: 

You are using the same URL for opening your SPSites

using (SPSite sourceSite = new SPSite(sUrl))
using (SPSite destinationSite = new SPSite(sUrl))

Have you tried the MSDN article? http://msdn.microsoft.com/en-us/library/ms470176.aspx

Phill Duffy
WTF! This gets filed under the "I'm a complete idiot" category! Thank you!
senfo
@Phil, Microsoft's very first example at that page leaks the site collection by combining two disposable types into one call. I just submitted community content to mention that.
Jesse C. Slicer
@Jesse - very good point and thanks for submitting content to MSDN, it helps us all out at some point or another@senfo - It's always good having a second pair of eyes on our code!
Phill Duffy
+2  A: 

In addition to the correct answer above, you should definitely be disposing of your SPWeb objects as well:

public static void MoveDocument(Uri sourceUrl, Uri destinationUrl)
{
    string sUrl = sourceUrl.ToString();
    string dUrl = destinationUrl.ToString();

    using (SPSite sourceSite = new SPSite(sUrl))
    using (SPSite destinationSite = new SPSite(dUrl))
    using (SPWeb sourceWeb = sourceSite.OpenWeb())
    using (SPWeb destinationWeb = destinationSite.OpenWeb())
    {
        SPFile sourceFile = sourceWeb.GetFile(sUrl);
        SPFolder destinationFolder = destinationWeb.GetFolder(dUrl);

        MoveDocument(sourceFile.ParentFolder, destinationFolder, sourceFile.Name);
    }
}
Jesse C. Slicer
Well spotted on those leaks - it's always worth running SPDisposeCheck http://code.msdn.microsoft.com/SPDisposeCheck
Phill Duffy