Bitsian
Bitsian

Reputation: 2258

How to fetch file names inside a folder of a Sharepoint Document Library in C#?

I have a document Library - "Artifacts" on my sharepoint server. And inside the library , I have a few folders. I want to fetch the names of all the files residing inside a folder. I am using Lists.asmx webservice for getting this info. But I have only been able to get the names of the folders but not the names of the file inside each folder. Below is the code for getting names of the folders. If there is a better approach to getting file names instead of Lists.asmx then please suggest it with some sample code. Otherwise please let me know how to fetch file names inside a folder using Lists.asmx webservice.

public Collection<string> GetFileNamesFromList(string sitePath, string folderName)
    {
        Collection<string> artifactsList = new Collection<string>();

        string innerhtml = string.Empty;
        string listServiceURL = string.Format("{0}{1}", sitePath, this.spserviceInfo.ListserviceUri);
        Lists listWS = new Lists(listServiceURL);
        listWS.UseDefaultCredentials = true;
        listWS.Url = listServiceURL;

        XmlDocument xmlDoc = new XmlDocument();
        XmlNode artifactQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
        XmlNode artifactViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
        XmlNode artifactQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
        artifactQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
        artifactViewFields.InnerXml = "";
        artifactQuery.InnerXml = "";

        XmlNode ndListItems = listWS.GetListItems("Artifacts", null, artifactQuery, artifactViewFields, null, artifactQueryOptions, null);

        XmlNodeList oNodes = ndListItems.ChildNodes;

        foreach (XmlNode node in oNodes)
        {
            XmlNodeReader objReader = new XmlNodeReader(node);

            while (objReader.Read())
            {
                if (objReader["ows_LinkFilename"] != null)
                {
                    var folder = objReader["ows_LinkFilename"].ToString();

                    artifactsList.Add(folder);
                }
            }
        }

        return artifactsList;
    }

Upvotes: 0

Views: 2926

Answers (1)

Milind
Milind

Reputation: 1955

Try the following code to get the items based on the folder

using(SPSite site = new SPSite("site url"))
{
  using(SPWeb web = site.OpenWeb())
  {
    SPFolder folder = web.GetFolder("/Docs/folder1");
    if(folder.ItemCount > 0)
    {
      SPList list = web.Lists.TryGetList("ListName");
      SPQuery query = new SPQuery();
      query.Folder = folder;
      SPListItemCollection = list.GetItems(query);
    }
  }
}

Upvotes: 1

Related Questions