0
votes

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?

2

2 Answers

4
votes

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

2
votes

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);
    }
}