Monday, October 28, 2013

Upload files to libraries using SharePoint services

We can use copy.asmx SharePoint web service to upload files when we can’t use SharePoint object model.
It’s very simple. you need to do something like below.
   1: const string webUrl = "http://sp13:8080/sites/hr/";
   2: const string sourceUrl = @"C:\Copy\emp.doc";
   3: string[] destinationUrl = { @"http://sp13:8080/sites/hr/Documents/emp.doc";
   4: CopyService.CopyResult[] resultArray;
   5: byte[] fileContents;
   6:  
   7:  var copyService = new CopyService.Copy
   8:   {
   9:     Url = webUrl + "/_vti_bin/copy.asmx",
  10:     Credentials = System.Net.CredentialCache.DefaultCredentials
  11:   };
  12:  
  13:  
  14:  var filedInfo = new CopyService.FieldInformation
  15:   {
  16:     DisplayName = "Title",
  17:     Type = CopyService.FieldType.Text,
  18:     Value = "Test"
  19:   };
  20:  
  21: //add values to fields in the library using fieldInfoArray array
  22: CopyService.FieldInformation[] filedInfoArray = { filedInfo };
  23:  
  24: //upload file using a file stream
  25: using (var stream = new FileStream(sourceUrl, FileMode.Open, FileAccess.Read))
  26:  {
  27:    fileContents = new Byte[stream.Length];
  28:    var read = stream.Read(fileContents, 0, Convert.ToInt32(stream.Length));
  29:    stream.Close();
  30:   }
  31:  
  32: var copyResult = copyService.CopyIntoItems(sourceUrl, destinationUrl, filedInfoArray, fileContents, out resultArray);

1 comment:

Petter Marry said...
This comment has been removed by the author.