How to fetch folders and subfolders from sharepoint document library

 I have document library with name . Under "Documents" there are some folders.Under some folders there are some subfolders.
I need to fetch the folders in to dropdown list. IF I select some folder in dropdownlist,I need to fetch subfolders of that folder to some other dropdownlist.
How to acheive this

The below function get the folder name and id of subfolder where items stored folder = item.folder.  Initially it will be null.
static
string GetParentFolder(SPListItem itemToFind,
SPFolder folder) 
SPQuery query =
new SPQuery();
query.Query = "<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">"+ itemToFind.ID +"</Value></Eq></Where>";
query.Folder = folder;
query.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection items = itemToFind.ParentList.GetItems(query);
int intpartentFolderID=0 ;
if (items.Count > 0)
foreach (SPListItem item
in items)
SPFile f = item.Web.GetFile(item.Url);
string test11 = f.ParentFolder.Name;
intpartentFolderID = f.ParentFolder.Item.ID;
return (intpartentFolderID.ToString());
         return (intpartentFolderID.ToString());    

Similar Messages

  • Download older version of a file from SharePoint Document Library using CSOM and 404 error

    Hi,
    I am trying to download previous versions including Major and Minor versions of documents from SharePoint Online using CSOM. I get 404 error when I try to download the file. I found several posts on various discussion forums where people are getting same
    error but none of those have any solution/answer. Below is one of the threads and sample code I have tried that results in 404 error. If I use the link in browser directly, I am able to download the file. Also I am able to download the current version of file
    using CSOM without any problem, it is only the older versions that give me 404 in CSOM.
    http://qandasys.info/how-to-download-the-historical-file-version-content-using-csom/
    public int GetStreamFromFile(string docid, string lib, string fileurl, ClientContext clientContext, int iuserid, string Version, bool isCurrrent)
    if(!isCurrent)
    List LibraryName = clientContext.Web.Lists.GetByTitle(lib);
    clientContext.Load(LibraryName);
    clientContext.ExecuteQuery();
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml = "" + fileurl +
    Microsoft.SharePoint.Client.ListItemCollection collListItem = LibraryName.GetItems(camlQuery);
    clientContext.Load(collListItem, items => items.Include(item => item.Id, item => item["FileLeafRef"], item => item["LinkFilename"],
    item => item["FileRef"], item => item["File_x0020_Size"], item => item["DocIcon"], item => item.File.Versions));
    //clientContext.Load(collListItem);
    clientContext.ExecuteQuery();
    foreach (Microsoft.SharePoint.Client.ListItem oListItem in collListItem)
    //string fileurl1 = (string)oListItem["FileRef"];
    //string filename = (string)oListItem["LinkFilename"];
    foreach (FileVersion version in oListItem.File.Versions)
    if (Version == version.VersionLabel)
    //Added excutequery to get object one more time as per blog
    //http://social.technet.microsoft.com/Forums/de-DE/sharepointdevelopmentprevious/thread/88a05256-8694-4e40-863d-6c77512e079b
    clientContext.ExecuteQuery();
    FileInformation fileInformation = ClientOM.File.OpenBinaryDirect(clientContext,version.Url);
    bytesarr = ReadFully(fileInformation.Stream);
    Darwaish

    Hi,
    According to your description,
    I know you want to get older version of a file from SharePoint Document Library using Client Object Model.
    The following code snippet for your reference:
    public void GetVersions()
    ClientContext clientContext = new ClientContext(“http://SPSite”);
    Web site = clientContext.Web;
    clientContext.Load(site);
    clientContext.ExecuteQuery();
    File file = site.GetFileByServerRelativeUrl(“/Shared Documents/mydocument.doc”);
    clientContext.Load(file);
    clientContext.ExecuteQuery();
    ListItem currentItem = file.ListItemAllFields;
    clientContext.Load(currentItem);
    clientContext.ExecuteQuery();
    FileVersionCollection versions = file.Versions;
    clientContext.Load(versions);
    clientContext.ExecuteQuery();
    if (versions != null)
    foreach(FileVersion _version in versions)
    Console.WriteLine(“Version : {0}”,_version.VersionLabel);
    More information:
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.file.versions.aspx
    Best Regards,
    Dennis Guo

  • How to extract audit log data from every document library in site collection using powershell?

    Hi All,
    I have n number of document library in one site collection,
    My query is- How to extract audit log data from every document library in a site collection using powershell?
    Please give solution as soon as possible?

    Hi inguru,
    For SharePoint audit log data, These data combine together in site collection. So there is no easy way to extract audit log data for document library.
    As a workaround, you can export the site collection audit log data to a CSV file using PowerShell Command, then you can filter the document library audit log data in Excel.
    More information:
    SharePoint 2007 \ 2010 – PowerShell script to get SharePoint audit information:
    http://sharepointhivehints.wordpress.com/2014/04/30/sharepoint-2007-2010-powershell-script-to-get-sharepoint-audit-information/
    Best Regards
    Zhengyu Guo
    TechNet Community Support

  • Exporting of pictures with folders and subfolders from Aperture

    I was importing folders with subfolders structure to Aperture 3.
    Is possible later export my pictures from structure in Aperture to folders and subfolders with same structure like it was before importing to Aperture?
    Thanks.
    Roman

    I'm assuming you imported using managed files and not referenced files? If referenced (leaving files in place), then your files are in the same folder structure as before.

  • How to filter the Files from SharePoint Document Library based upon cloumn value

    Hi
    I should filter the files from document library. I have column called "Print Status" for the document library the value would be either "Yes" or "No".
    Now i should filter out the files which has "Print Status" as a "Yes".
    I am using SPFolder and SPFile from SharePoint Object Model to traverse the file in doc library.
    How could i do it?
    My Sample code:
    foreach (SPFolder childFolder in folder.SubFolders)
      if (childFolder.Name != "Forms")
        AspControls.TreeNode trn = new System.Web.UI.WebControls.TreeNode(childFolder.Name, "", "~/_layouts/images/itdl.gif", childFolder.ServerRelativeUrl.ToString(), "");
        newNode = TraverseFiles(childFolder, trn);
                                // add the new node to the tree
                                rootNode.ChildNodes.Add(newNode);
                        // loop through the files
                        foreach (SPFile childFile in folder.Files)
                            // create a new node and add to the tree
                            AspControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode(childFile.Name + " (" + childFile.TimeLastModified.ToShortDateString()
    + ")", Convert.ToString(childFile.Item["ID"]), "~/_layouts/images/" + childFile.IconUrl, childFile.ServerRelativeUrl.ToString(), "");
                            rootNode.ChildNodes.Add(childNode);
    Thanks
    Poomani Sankaran.

    Why do you transvers the file an not use a camp query? In a CAML query you can filter the print status and are able to get all files and folder objects at once.
    Check out the following post: http://social.msdn.microsoft.com/Forums/sharepoint/en-US/8c45b5e2-1fb8-435c-a97d-1d8c6d288d4c/caml-query-to-query-all-the-files-and-folders-in-document-library?forum=sharepointdevelopmentprevious
    Kind regards
    Stefan
    http://www.n8d.at/blog
    Follow me on Twitter: StFBauer |
    n8design
    Microsoft Community Contributor 2011 / 2012
    MCTS - SharePoint / WSS Configuration and Development

  • Advice needed for provider hosted web application - authentication and access to SharePoint document library

    I haven't done SharePoint 2013 development with claims so I apologize in advance if my assumptions and questions are way out in left field.
    I'm trying to understand SharePoint 2013 claims authentication for a scenario that involves:
    A SharePoint provided hosted (web forms) app that will pull information and assets (e.g. PDFs) from SharePoint into the web page.
    It will be a VS 2012 solution with asp.net.identity feature.
    Security will be set for internal users, federated external users and forms-based external users.  Based on their security and (claim type) role it will define what information and assets that can be retrieved from SharePoint
    I have looked through MSDN and other sources to understand.
    This one helped with my understanding 
    Federated Identity for Web Applications and assumed that the general concept could be applied to forms-based identity for non-Federated external users .
    What I have now:
    VS 2012 solution web forms application set to Provider Host with asp.net.identity feature and its required membership tables.
    I can create new users and associate claims to the new user.
    I can log in with a user from the membership tables and it will take me to a default.aspx page.  I have added code to it that displays the claims associated to a user.
    For POC purposes I'd like to retrieve documents that are associated to this user from the default.aspx page.
    This is where I am having trouble understanding:  Is my understand correct?
    Internal users
    since they are internal on the network i am assuming that they would already have access to SharePoint and they would already be configured to what documents that they have available to them.
    Federated external users & Forms authentication external users
    it seems to me that the authentication for external users are separate from SharePoint authentication process.
    changes to the configuration settings are necessary in SharePoint, IIS, web application.
    I believe this is what i read.
    claims processes (e.g. mappings) need to be set up in SharePoint
    as long as external users are authenticated then things are ok b/c they would have claims associated to the user and the configuration in SharePoint takes are of the rest.
    This statement bothers me because I think it's wrong.
    So basically i'm stuck with if my understanding is correct: once a user is authenticated either by federated identity or asp.net.identity authentication that it should go to the provider hosted default.aspx page because the claim is authenticated and means
    that it should have access to it and the SharePoint document library based on some claim property.  I could then write the calls to retrieve from a document library and SharePoint will know based on some claim property that the logged in user can only
    access certain documents.
    It just sounds too good to be true and that i'm missing something in the thought process.
    Thanks in advance for taking the time to read.
    greenwasabi

    Hi GreenWasabi,
    i agree this is an interesting topic to discuss,
    as you can check from the article, you may check this example from the codeplex:http://claimsid.codeplex.com/
    when i thinking regarding this topic, its looks like an environment with multiple of realms,
    from what you understand, its correct that all the authentication is based from the provider, so for example i have a windows live ID and internal ID, then when i login windows live ID, it will be authenticated using windows live ID server.
    here is the example for the webservice:
    http://claimsid.codeplex.com/wikipage?title=Federated%20Identity%20for%20Web%20Services&referringTitle=Home
    as i know, if you using this federated, i am not quite sure that you will need to go to the provider page literally, perhaps you can check this example if we are using azure:
    http://social.technet.microsoft.com/wiki/contents/articles/22309.integrating-windows-live-id-google-and-facebook-accounts-with-sharepoint-2013-white-paper.aspx
    Regards,
    Aries
    Microsoft Online Community Support
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • How to fetch Header and Payload from a MimeMessage

    Hi,
    I have created a MimeMessage using an InputStream 'ins' like this
    MimeMessage mimeMsg = new MimeMessage(Session.getInstance(new Properties(), null), ins);This MimeMessage now looks like as shown below:
    Message-ID: <30289364.1195019945580.JavaMail.rishi@ap00475>Mime-Version: 1.0Content-Type: multipart/related;      boundary="ERCOT-XML-DATA";     Type="Application/X-ERCOT-MARKETS"--ERCOT-XML-DATAContent-Type: Application/XMLContent-Transfer-Encoding: 7bit<.....XML header....>--ERCOT-XML-DATAContent-Type: Application/XMLContent-Transfer-Encoding: 7bit<.....XML payload....>--ERCOT-XML-DATA--How can I get the above message to look like a proper MIME message (as shown below)? I tried using the method parse(), but it doesn't seem to do anything.
    Message-ID: <13665843.1194849042656.JavaMail.rishi@ap00475>
    Mime-Version: 1.0
    Content-Type: multipart/related;
         boundary="ERCOT-XML-DATA";
         Type="Application/X-ERCOT-MARKETS"
    --ERCOT-XML-DATA
    Content-Type: Application/XML
    Content-Transfer-Encoding: 7bit
    <.....XML header....>
    --ERCOT-XML-DATA
    Content-Type: Application/XML
    Content-Transfer-Encoding: 7bit
    <.....XML payload....>
    --ERCOT-XML-DATA--Also, how can I fetch the XML headers and the XML payload from this message? It would be great if you could tell me which methods in particular will be useful for this?
    Thanks,
    Rishi

    Hi bshannon,
    Here is my code. Here I am trying to create an inputstream from a mime message and vice versa. But while creating the Mime message back from the inputstream, it does not give the linebreaks. It looks like one single line of string. Also I am not sure how I can fetch the XML header and payload from this message.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
              mimeEncodedMsg.writeTo(bos);
              byte[] ba = bos.toByteArray();
              ByteArrayInputStream bin = new ByteArrayInputStream(ba);
              BufferedReader inputReader = new BufferedReader(new InputStreamReader(bin));
              StringBuffer serverResponse = new StringBuffer();
                             while ( inputReader.ready() )
                                  serverResponse.append( inputReader.readLine() );
                             inputReader.close();
    // -----------------MIME conversion to InputStream done----------------------     
              BufferedReader serverReader = new BufferedReader( new StringReader (serverResponse.toString()));
              StringBuffer servResp = new StringBuffer();
                   servResp.append( serverReader.readLine());
              serverReader.close();
              byte[] ba1 = servResp.toString().getBytes();
              ByteArrayInputStream bin1 = new ByteArrayInputStream(ba1);
              MimeMessage mimeDecodeMsg = new MimeMessage(Session.getInstance(new Properties(), null), bin1);
              mimeDecodeMsg.writeTo(new FileOutputStream("C:\\MimeTest2.txt"));Any idea why this is happening?
    Thanks,
    Rishi

  • How to build folders and subfolders without duplicating photos everywhere

    How do you organize photos in albums, and group albums into one "title"?  For example, a trip to Europe divided into albums for visits to different cities (without duplication).  I really want a Title -- then albums under that.

    Your question is not clear - what exactly do you mean by "group albums into one 'title'"?
    The general answer to your question is to simply use albums and folders - folders hold albums and/or other folders and albums hold photos - there is no duplication of anything - albums are pointer to photos in your library and are simply one way to view your photos
    So you can easily have a set of folders and albums like
    Vacations
         Europe
            France
               City One album
               City Two album
            England
              City One album
              City Two album
          France
              City One album
              City Two album
        North America
           Mexico
              City One album
              City Two album
           Canada
              City One album
              City Two album
          United States
               Missouri
                  City One album
                  City Two album
    And so on - that is exactly what you want to do i believe
    LN

  • How to know whether file is modified or metadata from SharePoint Document Library version history

    I have uploaded a document in document library. I am writing code to retrieve the items from the library only if document is modified, not the metadata.
    So if for an item only metadata is modified then it should not come, if document is modified then it should come. I tried from version history but it doesnt work. Any idea?
    Mark ANSWER if this reply resolves your query, If helpful then VOTE HELPFUL
    INSQLSERVER.COM
    Mohammad Nizamuddin

    Each file has an associated SPListItem which contains the metadata. See if the SPFile.TimeLastModified reflects the file and not the metadata.
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.timelastmodified.aspx
    Dimitri Ayrapetov (MCSE: SharePoint)

  • Issues opening PDF files from SharePoint document library reader/pro 11.0.5

    Hello,
    We have a sharepoint 2010 enviroment and recently upgraded our Acrobat X11 installs ( both reader/std/pro) to version 11.0.5.
    We have a mixture of WIndows 7 32/64Bit IE 8 and IE 9 machines
    After upgrading to 11.0.5 when users click a pdf file in a SP document libary one of two things happens depending if they have the
    Adobe Reader Plugin Enabled or not
    If the Adobe Reader Plugin is enabled, they will not get prompted to run/save the pdf file and it will not open in a new tab in the browser
    If the Adobe Reader Plugin is disabled, they will get a popup window that has the correct URL to the PDF in the address bar but they will not be prompted to save or run the file.
    If they click in the addrss bar and press enter the pdf will then load in the external reader/acrobat application.
    This issue started with 11.0.5 updates, rolling people back to 11.0.4 fixes the issue.
    I have attempted everything I can think of including rebuilding new machines with our image.
    Has anyone see issues like this with the 11.0.5 update?

    If a bug is confirmed, a fix may be delivered in the next release (can't promise). For a similar issue caused by a Microsoft bug, see http://forums.adobe.com/message/6106294#6106294.
    Ben

  • Export Datatable to Excel 2010 format and Save in SharePoint Document library ,and whn opening file getting error "WorkBook may be in unsupported file format "

    im converting stringwriter objec to Memory stream and saving this as .xlsx uploading file in library ,but when i try to open the file im getting error as below
    WorkBook may be in unsupported file format
    and when trying to open in excel getting message as
    Excel cannot open file  because file extention or file format is not valid .verify thet the file has not been corrupted and file extensions match file format

    May be you can use this approach:
    http://www.c-sharpcorner.com/UploadFile/pandeypradip/export-data-into-excel-in-a-pre-defined-template-using-strea/

  • Move a folder, sub-folders, and documents under that folder from one document library to another within a Workflow

    Hello,
    I'm building a workflow in SharePoint Designer 2010 (Unfortunately we are not on 13 yet), and in that workflow I need to move a folder (with all it's sub-folders and items) from one document library to another document library.
    I tried a copy item but that kept failing, I checked content type, columns, and permission and it all looks good.
    the other option I started looking into is to Create the folder in the document list and them move all the items under that folder to the new folder. However I can't figure out how to loop through each items in that folder.
    Has this issue been addressed? or does someone has a solution.
    I looked and searched and all I found was tutorials on moving single items into a folder, but not entire folders.
    Thanks
    Hani

    Why to take pain in creating a workflow that copies folders, sub-folders and all of its contents from one document library to another.
    Simply open your source and destination document library in Windows Explorer mode and start copying your folder, sub-folders and contents that you want to copy out of the box.
    You will find "Open with Explorer" button under the Library tab on the ribbon of document library.
    Please remember to click 'Mark as Answer' on the reply if it helps you

  • How to find list or folder name from SharePoint document URL

    I'm implementing the SharePoint client object model in my VSTO application in .NET framework 4.0(C#).
    Actually we open MS Word files from SharePoint site, we need to create a folder inside the opened documents list/folder and after it we want to upload/add some files to that created folder.
    My problem is that how to get list name/title and folder name of opened document by using the documents URL or Is there an another option to find the list or folder name of opened document.
    Any help will be appreciable.

    In document Library you can get the name of document library directly in URL. for folder name you can try below:
    using System;
    using Microsoft.SharePoint;
    namespace Test
    class ConsoleApp
    static void Main(string[] args)
    using (SPSite site = new SPSite("http://localhost"))
    using (SPWeb web = site.OpenWeb())
    if (web.DoesUserHavePermissions(SPBasePermissions.BrowseDirectories))
    // Get a folder by server-relative URL.
    string url = web.ServerRelativeUrl + "/shared documents/test folder";
    SPFolder folder = web.GetFolder(url);
    try
    // Get the folder's Guid.
    Guid id = folder.UniqueId;
    Console.WriteLine(id);
    // Get a folder by Guid.
    folder = web.GetFolder(id);
    url = folder.ServerRelativeUrl;
    Console.WriteLine(url);
    catch (System.IO.FileNotFoundException ex)
    Console.WriteLine(ex.Message);
    Console.ReadLine();
    http://msdn.microsoft.com/en-us/library/office/ms461676(v=office.15).aspx
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/801d1a06-0c9b-429b-a848-dd6e24de8bb9/sharepoint-webservice-to-get-the-guid-of-the-folder?forum=sharepointdevelopmentlegacy
    You can also try below:
    http://blogs.msdn.com/b/crm/archive/2008/03/28/contextual-sharepoint-document-libraries-and-folders-with-microsoft-dynamics-crm.aspx
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/d2d5d7cf-9bbd-4e0f-a772-ecdce4e6149f/how-to-fetch-document-guid-from-sharepoint-document-library-using-sharepoint-web-service?forum=sharepointdevelopmentlegacy
    http://stackoverflow.com/questions/2107716/how-to-get-guid-of-a-subfolder-in-a-document-library-programmatically

  • Linking a programmatically created folder in SharePoint Document Library.

    I have created folders within a document library using InfoPath & C#. To that folder I uploaded several documents using several file attachment controls within the same InfoPath Form using the code behind the form.  Now I want to create an Hyperlink
    to each folder in another document folder's column that has the relationship with the previously created folder.
    When I googled I saw there are lot of articles to create Folders ,uploading documents to folders in a SharePoint Library but I cannot understand how to create a hyperlink in a SharePoint Document Library field column.
    Could someone help me to solve this matter?
    Thanks,
    Regards,
    Chiranthaka

    Why don’t you create a hyperlink column to store the hyperlink value, or you can use a lookup column to lookup the related folder item?
    Qiao Wei
    TechNet Community Support

  • Rename a File in a SharePoint document library through Client object model

    Hi,
    How  to Rename a File in a SharePoint document library through Client object model?
    Thanks
    Poomani Sankaran

    Hi,
    According to your description, you want to rename file in the document library using SharePoint Client Object Model.
    Here is a code snippet works well in my environment for your reference:
    static void Main(string[] args)
    string url = "http://sp2013sps/sites/test/";
    ClientContext clientContext = new ClientContext(url);
    Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Documents");
    clientContext.Load(spList);
    clientContext.ExecuteQuery();
    if (spList != null && spList.ItemCount > 0)
    Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml =@"<View> <Query> <Where><Eq><FieldRef Name='LinkFilenameNoMenu' /><Value Type='Computed'>New Microsoft Word Document.docx </Value></Eq></Where> </Query> <ViewFields><FieldRef Name='Title' /></ViewFields> </View>";
    ListItemCollection listItems = spList.GetItems(camlQuery);
    clientContext.Load(listItems);
    clientContext.ExecuteQuery();
    listItems[0]["Title"] = "word.docx";
    listItems[0]["FileLeafRef"] = "word.docx";
    listItems[0].Update();
    clientContext.ExecuteQuery();
    More information about SharePoint Client Object Model:
    http://msdn.microsoft.com/en-us/library/office/ee537247(v=office.14).aspx
    http://www.codeproject.com/Articles/399156/SharePoint-Client-Object-Model-Introduction
    http://www.learningsharepoint.com/2010/07/12/programmatically-upload-document-using-client-object-model-sharepoint-2010/
    Best regards

Maybe you are looking for

  • How to use the cancel button in showInputDialog

    um how would i go with overriding the cancel button's deafult function in JOptionPane.showInputDialog? in my code: package alphaOne; * this program takes in a number and gets the factorial of that number import javax.swing.*; public class Factorial {

  • Need help to COMPLETELY uninstall HP drivers & software fm pc running Win 7

    I am having difficulty with completely removing and uninstalling the HP drivers and software from my Dell Inspiron 830. I am running Windows 7. I have attempted a number of times use the uninstall feature under programs and applications in Windows. 

  • HR Forms

    Hi experts, I am new to HR Forms.Can any one tell me What is it?why it is used? and how to create a Layout for the form in SAP Form Builder. I already have the material for HR Form workplace and Editor.I want the use and steps and also about the layo

  • Need Time in Words

    Hi, I want time in words Ex.. 10.30 Ten hours thirty minutes please help.. Thanks Adina

  • InstallApplication MDM command is not working

    My MDM profile has FULL ACCESS rights (8191) I don;t get any error in IPCU console but "InstallApplication" won;t work. IPCU console says....  Aug 23 15:58:07 Satish-iPad mdmd[281] <Notice>: (Note ) MDM: Transaction completed. Status: 200 Aug 23 15:5