Search This Blog

Thursday, October 18, 2018

SharePoint Picture Library -Get Image from Folder using CAML Query in C#


public DataTable GetFolderImageFromPicLib(string folderPath)
        {
           
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("Keywords", typeof(string));
            dt.Columns.Add("RequiredField", typeof(string));
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("FileName", typeof(string));
            dt.Columns.Add("FolderPath", typeof(string));
            dt.Columns.Add("FileDirRef", typeof(string));
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                      

                        SPPictureLibrary lib = (SPPictureLibrary)web.Lists.TryGetList("My Pic Library");
                       // folderPath = "/sameple/" + lib.Title + folderPath;
                        folderPath = "/" + lib.Title + folderPath;
                        if (lib != null)
                        {
                            SPQuery query = new SPQuery();
                            query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                  "<Query>" +
                  "<Where>" +
                              "<Eq>" +
                                  "<FieldRef Name=\"FileDirRef\" />" +
                                  "<Value Type=\"Text\">"+ folderPath + "</Value>" +
                               "</Eq>" +
                  "</Where>" +
                  "</Query>" +
                  "</View>";
                            DataRow row;

                            SPListItemCollection lstImages = lib.GetItems(query);
                            foreach (SPListItem item in lstImages)
                            {
                                string folderName = Convert.ToString(item["RequiredField"]);
                                row = dt.NewRow();
                                row["ID"] = item["ID"];
                                row["FileDirRef"] = item["FileDirRef"];
                                row["Keywords"] = item["Keywords"];
                                row["RequiredField"] = item["RequiredField"];
                                row["FolderPath"] = folderName.Remove(folderName.LastIndexOf('/') + 1);
                                row["Title"] = item["Title"];
                                row["FileName"] = item["FileName"];
                                dt.Rows.Add(row);
                            }

                        }
                    }
                }
            });
            return dt;
        }

No comments:

Post a Comment