Monday, April 22, 2013

Save File to Sharepoint

This code shows how to use c# to send a file to Sharpoint using the WCF REST Services. 

Create service reference

Add a service reference to the C# Windows form project. The URL is 

http://test.sharepoint.nterprise.net/servicetesting/_vti_bin/ListData.svc

Create a Sharepoint Gateway class


        public string SendByteArrayToSharepoint(Byte[] bytes, string fileName)
        {
            try
            {
                string sharepointUrl = (string)Settings.Default["SharepointUrl"];
                Stream fileStream = new MemoryStream(bytes);

                ServiceTestingDataContext context = new ServiceTestingDataContext(_sharepointUri);
                context.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                string slug = Path.Combine(@"/servicetesting/DropBox/", fileName);
                string contentType = NtfsUtilities.GetMimeFromByteArray(bytes);
                DropBoxItem dbi = new DropBoxItem()
                {
                    ContentType = contentType,
                    Name = Path.GetFileName(fileName),
                    Source = "source",
                    TargetSystem = "targetSystem",
                    Reference = "reference",
                    Notes = "notes",
                    OriginalFilename = Path.GetFileName(fileName),
                    Path = fileName
                };

                context.AddToDropBox(dbi);
                context.SetSaveStream(dbi, fileStream, true, contentType, slug);
                context.SaveChanges();
                //at this point, the document ID is NULL, as it was assigned on the server.
                //Calling context.LoadProperty(dbi, "DocumentID"); causes the dbi object to be refreshed
                context.LoadProperty(dbi, "DocumentID");
                return dbi.DocumentID;
            }
            catch (Exception ex)
            {

                throw;
            }
        }


Use the class

Read the file into a byte array. then call the method SendByteArrayToSharepoint:
string SharepointPDFUrl = WriteBytesToSharepoint(theByteArray, "fileName.pdf");


No comments:

Post a Comment