Saturday 22 October 2011

Copying File from one Doc Library to Another - Problem Solved

I forgot to update about this. I solved that problem that had me removing several hairs at the follicle.

In order to copy the file from one place to the other, I had to create a using block for the source site and then the target site. Thus (note that this was in a separate class file from the event handler so I did not have access to the properties object and had to pass the IDs in as parameters):

public static void CopyFile (Guid listID, int itemID, string sourceUrl, string targetUrl, Guid targetListID)
{
     try
     {     
         using (SPSite sourcesite = new SPSite(sourceUrl))
         {
             using (SPWeb sourceWeb = sourceSite.OpenWeb())
             {
                  SPList list = web.Lists[listID];
                  SPListItem item = list.Items[itemID];
                  SPFile file = item.File;
                  //Here was where my error started
                  //I instantiated the file out of scope
                  byte[] binFile = file.OpenBinary();
                  
                  //OPEN TARGET SITE AND WEB HERE
                  using (SPSite targetSite = new SPSite(targetUrl))
                  {
                       using (SPWeb targetWeb = targetSite.OpenWeb())
                       {


                           //get the target list
                           //create SPFolder object
                           //this is like a SPList object
                           //but concerned only with the copying of files
                           folder.Files.Add(binFile);
                       }
                  }

     
             }
         }
     }
}


My error appeared to be where I declared the binary array. When I declared it within scope of the target site everything appeared to work perfectly, even though I was just streaming the file on the other site like before. I have no idea why a binary stream should lose scope, it's only an array, but I could not make it work for a non-admin user.


Please note that I haven't put in the target file copying code in detail as I am working from memory here - but it needs to be done using the SPFolder object. The SPFolder objects points to the document library just like the SPList object, but only deals with the files. Because the SPList object only handles stuff on lists. It doesn't do files. Jobsworth of an object!

No comments:

Post a Comment