RSS LOGORss   Welcome Guest  Login Register
Welcome to our Blogs
Back Back
Subject


mag
2008/08/02 03:11PM
Copy File from a Document Library to another with new ContentType      Number of views: 1912

 

 

Hi, I was writing a sample project for the Ministry of how to copy a file from a source document library to a folder with a content type using the SharePoint API,
Here is the code, enjoy,
 
Guid ListId = newGuid(Request["ListId"].ToString()); //The ListId is sent by the Query String
SPWeb web = SPContext.Current.Web;
 
SPDocumentLibrary FromLibrary = (SPDocumentLibrary)web.Lists[ListId]; // Loading the list (document library
 
SPDocumentLibrary TargetLibraryrary = General.GetDocumentLibByRootFolderName(General.DoclibsArray[GetTypeValue() - 1]); ; // this is just my code to get the Target DocumentLibrary, just replace it with your code.
 
string[] targetData = drpCompanies.SelectedItem.Value.Split(newchar[] { '~' });   // again my code you just delete this line
SPListItem   targetfolder = TargetLibrary.Folders[newGuid (targetData[1])]; // I should get the right folder that I’m copying the file to.
 
  // the following few lines is adding multiple files that I have from the source folder to the target folder.
 
Hashtable ht = null// This is the HashTable is usend to store the content type of the file J 
foreach (ListItem item in lbFiles.Items)
{
    ht =newHashtable();
    string[] fileData = item.Value.Split(newchar[] { '~' });
    SPListItem listItem = FromLibrary.GetItemById(int.Parse(fileData[0]));
    byte[] data = listItem.File.OpenBinary(SPOpenBinaryOptions.SkipVirusScan) ; // Loading the file bytes
    ht.Add("ContentTypeId", "0x0101005AA1389ABED0E74EADD6318253F5431A0099CD30BEEA837143997FFC0531B30A33");// My own content type
    SPFile file = targetfolder.Folder.Files.Add(fileData[1] + ".pdf", data,ht,true); // Saving the file to the target folder
    file.Item["FileType"]=fileData[1]; // Update some of the content type’s properties.
    targetfolder.Update(); // at last, now you have your file stored in the target’s folder.
}
 
Hope it helps,
 
Battot