Monday, 9 March 2015

Read Sharepoint file(s) inside a folder

Read SharePoint file(s) in C#

Today I got a requirement to read a document inside a folder. I have integrated CRM with SharePoint and once we upload a document, list component creates a folder with the title appended with GUID of the record and places the files inside.

Here is the code to read the files from that folder.

using (ClientContext clientContext = new ClientContext(SharepointsiteURL))
                clientContext.Credentials = new System.Net.NetworkCredential(SharepointUsername, Sharepointpassword, "<Domain>");
                Web objWeb = clientContext.Web;
                List douLib = objWeb.Lists.GetByTitle("Case");
                CamlQuery caml = new CamlQuery();
                string strQuery = "<View Scope=\"RecursiveAll\"> " +
                    "<Query>" +
                    "<Where>" +
                                "<Eq>" +
                                    "<FieldRef Name=\"FileDirRef\" />" +
                                    "<Value Type=\"Text\"><Share Point Folder Relative URL></Value>" +
                                 "</Eq>" +
                    "</Where>" +
                    "</Query>" +
                caml.ViewXml = strQuery;
                ListItemCollection items = douLib.GetItems(caml);
                WebRequest objWebRequest;
                MemoryStream objMemStream;
                WebResponse objResponse;
                Stream fileStream;
                for (int intCount = 0; intCount < items.Count; intCount++)
                    // Get the path of
                    objWebRequest = WebRequest.Create(new Uri("<FileURL>"));
                    objWebRequest.Credentials = new System.Net.NetworkCredential(SharepointUsername, Sharepointpassword, "<Domain>");
                   objMemStream = new MemoryStream();
                        objResponse = objWebRequest.GetResponse();
                        fileStream = objResponse.GetResponseStream() as Stream;
                        objMemStream.Position = 0;
                        byte[] objByteArray = objMemStream.ToArray();
                       // System.IO.File.WriteAllBytes(@"\test.xlsx", objByteArray);
                    catch (Exception ex)
                        throw ex;

Happy CRM'ing

1 comment:

  1. Hello Gopinath,
    I really liked your post, can you tell me how do we need to retrieve the CRM Documents from Sharepoint site ?