none
Getting subfolder names without the full path within a folder in C#? RRS feed

  • Question

  • How to retrieve the subfolder names without the full path within a folder in C#?

    Files.GetDirectories(...) gets the folder names but with the entire path. Is there anything for just getting the FOLDER NAMES ONLY.

    Thank you
    Neil
    neil
    Friday, October 30, 2009 7:53 AM

Answers

  • Hi,

    You can use the following code.

                string path=@"D:\Kisisel\";
                foreach (string s in Directory.GetDirectories(path))
                {
                    Console.WriteLine(s.Remove(0,path.Length));
                }
    • Marked as answer by nilashis Friday, October 30, 2009 9:59 PM
    Friday, October 30, 2009 8:03 AM

All replies

  • Hi,

    You can use the following code.

                string path=@"D:\Kisisel\";
                foreach (string s in Directory.GetDirectories(path))
                {
                    Console.WriteLine(s.Remove(0,path.Length));
                }
    • Marked as answer by nilashis Friday, October 30, 2009 9:59 PM
    Friday, October 30, 2009 8:03 AM
  • Hi,
    Tamer small change in your code.
    name = s.Remove(0,s.LastIndexOf('\\')+1);

    Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you
    • Edited by Gnanadurai Friday, October 30, 2009 8:27 AM variable
    Friday, October 30, 2009 8:25 AM
  • Or even better, instead of using '\\' you could use:

    System.IO.Path.DirectorySeparatorChar

    Friday, October 30, 2009 12:00 PM
  • Even better:
    foreach (string folder in Directory.GetDirectories(path))
        Console.WriteLine(Path.GetFileName(folder));
    
    • Proposed as answer by docesam Friday, March 23, 2018 12:57 PM
    Friday, October 30, 2009 1:29 PM
  • Or just use the DirectoryInfo class to get all the information you want, including the folder name alone.
    Geert van Horrik - CatenaLogic
    Visit my blog: http://blog.catenalogic.com

    Looking for a way to deploy your updates to all your clients? Try Updater!
    • Proposed as answer by SandeepKumarV Monday, August 18, 2014 11:36 AM
    Friday, October 30, 2009 4:34 PM
  • Hi,
    Tamer small change in your code.
    name = s.Remove(0,s.LastIndexOf('\\')+1);
    

    Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you
    I know this is old, but I've been looking for this for a long time. Thanks.
    Thursday, October 20, 2016 1:35 PM
  • This worked amazing

    Tuesday, November 21, 2017 7:59 PM