How to get a directory listing in C#

Name: C# class to return a list of files and folders.
Description: Pass in the base directory you want a list of files and folders for.
Time: 5 minutes

In this example you will learn how to loop through directories and files.

Step 1 – Background.

First off, there are probably many of these already out there in the public domain. However I developed mine in such a way that it is very easy to follow and understand.

The type of output that I want from this code is:

Quote Sample Run originally posted:
c: \hello.jpg
c: \hi.php
c: \foo\bar.exe
c: \foo\sheep.png
c: \thomas/tank-engine.mpg

From here on in, I assume you have created a new project.

Step 2 – Setup.

First off, we need to create a new class. To do this, click Project then Add Class. I named my class Files.cs

Now that we have our class, we need to add System.IO to our using list. We need this to use the .IO directive so we can iterate through files and folders.

We also need to add System.Collections to enable our class file to use ArrayLists (which I will explain why later).

To do this, at the top of the newly created Class file you will see code like

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Add the following two lines of code

Code:
using System.Collections;
using System.IO;

So now you should have code like

Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

Step 3 – Getting down to it

Here is the juicy part, the below code is the method that gets the directory listing. The method takes in 1 parameter which is the base directory (the directory to start the directory listing).

Code:
     public static string[] getFilesFromBaseDir(string baseDir)
     {
     List<string> fileResults = new List<string>();
     ArrayList directories = new ArrayList();

      // Add inital Directory to our ArrayList
      directories.Add(baseDir);

     // Loop while there is something in our ArrayList
      while (directories.Count > 0)
      {
      // Get directory from ArrayList
      string currentDir = directories[0].ToString();

      // Remove element from ArrayList
      directories.RemoveAt(0);

      // Add all files in this directory
     foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))
       {
         fileResults.Add(fileName);
           }

       // Add all directories in currentDir
     foreach (string dirName in Directory.GetDirectories(currentDir))
         {
          directories.Add(dirName);
           }
         }
      return fileResults.ToArray();
      }

The method first adds the parameter passed in to the ArrayList directories. Then we create a while loop which will run if directories has more than 0 elements.

We then set the string variable currentDir to the first element in the ArrayList. Then we remove the first element from the ArrayList.

Then we loop through all the files in currentDir and add them to fileResults.

Now we check if there are any directories in the directory currentDir. We add the directories to the ArrayListdirectories.

Finally we return fileResults as an array.

Step 4 – Usage

To get the files and folders of a directory you add the following code

Code:
string[] fileNames = Files.getFilesFromBaseDir("C:\\TestDirectory");

And to see it’s output you would have the following code

Code:
            foreach (string fileName in fileNames)
            {
                rtbFiles.Text += fileName + Environment.NewLine;
            }

So there you have it, by using this example you can get a directory listing in C#

Advertisements

118 responses to this post.

  1. We stumbled over here by a different web address and thought I should check things out. I like what I see so now i am following you. Look forward to checking out your web page repeatedly.

  2. nick web site content material. I bookmarked it to my bookmark website list and will also be checking again soon.

  3. Brilliant pages… just what am looking for….

  4. When are you going to post again? You really entertain a lot of people!

  5. Hey, I just hopped over to your webpage via StumbleUpon. Not somthing I might normally read, but I liked your thoughts none the less. Thank you for creating something worthy of browsing.

  6. Have you considered including several social bookmarking links to these sites. At least for bebo.

  7. When I open up your Feed it seems to be a ton of junk, is the problem on my side?

  8. When I originally commented I clicked the Notify me whenever new comments are added checkbox and currently each and every time a comment is added I get four messages with the same comment.

  9. The structure for your site is a little bit off in Epiphany. Even So I like your weblog. I might have to use a normal web browser just to enjoy it.

  10. Hi, I just hopped over to your web site via StumbleUpon. Not somthing I would typically read, but I liked your thoughts none the less. Thanks for creating some thing well worth reading.

  11. How do you make your blog look this awesome. Email me if you can and share your wisdom. Id appreciate it.

  12. Wanted to drop a remark and let you know your Feed is not functioning today. I tried including it to my Bing reader account and got nothing.

  13. Mate! This website is awesome! How do you make it look this good !

  14. Wanted to drop a comment and let you know your Feed isnt working today. I tried including it to my Google reader account and got absolutely nothing.

  15. Jesus Christ theres plenty of spammy feedback on this web page. Have you ever thought about attempting to eliminate them or putting in a extension?

  16. When are you going to post again? You really inform a lot of people!

  17. Cool post . Cheers for, commenting on this blog page dude! I will message you some time. I didnt know that!

  18. If you dont mind, exactly where do you host your website? I am looking for a great web host and your web site appears to be quick and up most the time

  19. salutations from across the ocean. detailed blog I will return for more.

  20. Very interesting information!Perfect just what I was searching for!

  21. This blog has inspired me to start focusing on my own blog

  22. Brilliant, thanks, I will subscribe to you RSS later.

  23. Hello, i feel that i noticed you visited my weblog so i came to “go back the prefer”.I am trying to to find things to enhance my site!I guess its adequate to use a few of your ideas!!

  24. Nice post. I was checking continuously this blog and I’m impressed! Very useful info particularly the last part 🙂 I care for such information a lot. I was looking for this particular info for a long time. Thank you and good luck.

  25. BTW, traffic also gets screwed up by things like the Boston and Marine Corps Marathon on Washington. If I wanted to I could get really upset at that but Ive volunteered to help out at the Washington event.

  26. Greetings! I simply want to provide a big thumbs way up for that wonderful advice you’ve here about this post. I’ll be returning to your site for additional in the near future. Simultaneously in case you are looking towards Web Marketing, please click my current blog page

  27. This publication has inspired me to start working on my own blog

  28. This blog is pretty cool. How was it made !

  29. I love your wp web template, where did you get a hold of it?

  30. I experimented with looking at your site on my ipod touch and the structure does not seem to be right. Might want to check it out on WAP as well as it seems most cell phone layouts are not working with your web site.

  31. If you dont mind, where do you host your weblog? I am hunting for a very good web host and your site seams to be fast and up almost all the time

  32. An interesting post right there mate ! Cheers for the post .

  33. When I start your Feed it appears to be a ton of nonsense, is the problem on my side?

  34. Im getting a javascript error, is anyone else?

  35. Whilst I actually like this publish, I believe there was an punctuational error close to the finish with the 3rd sentence.

  36. When I start your Feed it appears to be to be a ton of garbage, is the problem on my part?

  37. Re: Whomever made the remark that this was a great web site truly needs to possess their head examined.

  38. Good Stuff, do you currently have a flickr profile?

  39. excellent blog post, i obviously adore this site, keep it.

  40. I tried looking at your website in my mobile phone and the page layout doesnt seem to be correct. Might want to check it out on WAP as well as it seems most cellphone layouts are not working with your website.

  41. I think one of your current advertisements triggered my web browser to resize, you might well need to set up that on your blacklist.

  42. It’s best to take part in a contest for one of the best blogs on the web. I’ll suggest this site!

  43. Great post, there seems to be a lot of misinformation about mortgages going around but this was a no-fluff post. I appreciate it, cheers.

  44. My pinterest name is Devofry. The backlink is pinterest.com/devofry

  45. Excellent video Jeanette,

  46. This content articles are performing fantastic additionally to jam packed with remarkable information. I’d be blissful to hold on returning the following to guage to get a brand-new update.

  47. You can do all the stat analysis you want. Throw velocity readings in there too. The fact is he hasnt been the same pitcher since that spot start.

  48. Hi just thought i would inform you something.. This really is twice now i’ve landed in your blog during the last 21 days searching for totally unrelated things. Spooky or what?

  49. Hello there, just became aware of your blog through Google, and found that it’s truly informative. I am gonna watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  50. I have recently started a web site, the info you offer on this website has helped me tremendously. Thanks for all of your time & work.

  51. BetWoohoo! Im not the teacher type, so to indirectly help you is wonderfully happy-making. Thanks for letting me know and may it result in some crazy great racing for you this season.

  52. Just want to thank you for this text. This is kind of a thing I was looking for (Thanks Yahoo

  53. 15. When youve seen one shopping center youve seen a mall.

  54. Great goods from you, man. I’ve understand your stuff previous to and you are just extremely fantastic. I really like what you’ve acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I can not wait to read much more from you. This is really a wonderful web site.

  55. Pretty nice post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!

  56. Hi, i think that i saw you visited my blog thus i came to “return the favor”.I’m trying to find things to improve my site!I suppose its ok to use some of your ideas!!

  57. Hello There. I found your blog using msn. This is a really well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll definitely comeback.

  58. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently fast.

  59. Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a bit, but instead of that, this is great blog. A fantastic read. I’ll definitely be back.

  60. Thanks for giving your ideas on this blog. As well, a myth regarding the banking institutions intentions while talking about foreclosed is that the loan company will not take my repayments. There is a certain quantity of time which the bank will take payments every now and then. If you are far too deep inside the hole, they should commonly desire that you pay that payment entirely. However, i am not saying that they will not take any sort of repayments at all. Should you and the bank can have the ability to work anything out, the particular foreclosure method may end. However, in case you continue to miss out on payments underneath the new approach, the foreclosures process can just pick up from where it left off.

  61. Great articles & Nice a site.. youve gotten an ideal blog right here! would you prefer to make some invite posts on my blog? outstanding great terrific.

  62. I am happy that I found this web site, exactly the right information that I was looking for! .

  63. Hi I think that you have got a wonderful weblog going right here, I noticed it on Msn and plan on coming back again often for the info that you all are delivering.|Thank you for helping to make my morning a tiny tad better with this terrific page

  64. Very nice post. I just stumbled upon your blog and wished to say that I have truly enjoyed surfing around your blog posts. After all I’ll be subscribing to your rss feed and I hope you write again very soon!

  65. Nntp ‘s been around to get a quite a while. It really is even significantly older than the globe wide web- just what most everyone knows as being the

  66. Howdy! Do you use Twitter? Id like to follow you if that would be ok. Im absolutely enjoying your blog and look forward to new posts.

  67. When I view your Feed it simply gives me a page of weird text, is the problem on my reader?

  68. The subsequent time I read through a blogging site, I really hope that it doesnt disappoint me as much as this just one. I suggest, I’m sure it absolutely was my choice to go through, but I realistically considered youd have a little something intriguing to say. All I listen to is known as a bunch of whining about something that you might fix if you happen to werent very fast paced seeking awareness.

  69. Nntp ‘s been around for any quite a while. It truly is even more aged than the planet wide web- precisely what many people know as being the

  70. Netnews has been online to get a quite a while. Its even more aged than the planet wide web- just what most everyone knows since the

  71. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a bit, but other than that, this is great blog. A fantastic read. I will definitely be back.

  72. Netnews has been online for any long time. It truly is even over the age of the planet wide web- precisely what many people know because the

  73. Very interesting info!Perfect just what I was searching for!

  74. The People Have Spoken. They have had enough. The vote is the most powerful tool we possess, especially since most of those in Washington, are no longer listening to our voices, even in large numbers. A unified people, coming together for the right causes, will prevail, just as truth and not a lie will always prevail.

  75. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this hike.

  76. My wife and i were very thankful Ervin could round up his studies from your precious recommendations he was given from your own blog. It is now and again perplexing to just choose to be giving freely helpful tips that many others could have been selling. We remember we have got the website owner to give thanks to for that. All the explanations you made, the easy blog menu, the relationships your site give support to engender – it’s mostly sensational, and it’s really leading our son and us do think this subject matter is interesting, which is extraordinarily mandatory. Many thanks for all the pieces!

  77. […] week I posted an article on peHUB titled How to Create a Sustainable Entrepreneurial Community.  Here it is in its […]

  78. I just want to mention I am new to weblog and actually loved your web page. Very likely I’m going to bookmark your website . You really have fabulous articles. Thank you for revealing your web site.

  79. Netnews has been online for any while. Its even over the age of the planet wide web- precisely what nearly everyone knows as being the

  80. Gorgeous femme model. By the way you’ve got a educational internet site

  81. Netnews has been online to get a long time. Its even over the age of the entire world wide web- precisely what most everyone knows because the

  82. Nntp has existed to get a quite a while. It really is even more aged than the entire world wide web- exactly what most everyone knows since the

  83. […]please visit the sites we follow, including this one, as it represents our picks from the web[…]…

  84. […]always a big fan of linking to bloggers that I love but don’t get a lot of link love from[…]…

  85. Nntp has been online for the while. Its even over the age of the planet wide web- exactly what many people know because the

  86. indian wedding photographer in ny

  87. Great website. Lots of helpful information and facts below. I inside the early morning supplying it to several buddies ans additionally posting in delicious. As well as organically, thanks on your personal function!

  88. Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently quickly.

  89. I’m impressed, I must say. Actually rarely do I encounter a blog that’s each educative and entertaining, and let me let you know, you’ve gotten hit the nail on the head. Your concept is excellent; the difficulty is something that not sufficient persons are talking intelligently about. I’m very completely happy that I stumbled throughout this in my search for something relating to this.

  90. Howdy! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your blog and look forward to new posts.

  91. I like this site so considerably, saved to favorites .

  92. Great post at How to get a directory listing in C# Denno Secqtinstien Foundation. I was checking continuously this blog and I am impressed! Very useful info specially the last part 🙂 I care for such information much. I was seeking this particular information for a long time. Thank you and best of luck.

  93. With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My site has a lot of completely unique content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you know any ways to help stop content from being stolen? I’d genuinely appreciate it.

  94. hello!,I really like your writing so so much! proportion we communicate extra about your article on AOL? I need a specialist in this area to solve my problem. Maybe that is you! Having a look ahead to look you.

  95. Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, as well as the content!. Thanks For Your article about How to get a directory listing in C# Denno Secqtinstien Foundation .

  96. I do not know whether it’s just me or if perhaps everyone else experiencing problems with your site. It looks like some of the text within your posts are running off the screen. Can somebody else please comment and let me know if this is happening to them as well? This could be a problem with my internet browser because I’ve had this happen before. Thank you

  97. Internet is a source of information and knowledge. But there are so many sites in net which are nothing but gibberish. But when I visit your site – I felt that – in net there are lots of sites (like this) from where I can get lot of information too. And if I say truly – your site is fantastic. I’ve bookmarked your site in my browser; I hope in future days I’ll get more valuable information from your site.

  98. We are a group of volunteers and starting a new scheme in our community. Your website provided us with valuable information to work on. You’ve done an impressive job and our whole community will be thankful to you.

  99. Fantastic post however I was wanting to know if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit further. Thank you!

  100. very nice post, i certainly love this website, keep on it

  101. An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

  102. There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment’s pleasure, for the rest of their lives.

  103. I not to mention my buddies have been looking at the good information from your web blog and then quickly developed a horrible feeling I never expressed respect to the blog owner for those secrets. These boys had been as a result very interested to study all of them and now have absolutely been using them. Many thanks for simply being quite considerate and for getting certain important subject matter millions of individuals are really wanting to be informed on. Our own honest regret for not expressing gratitude to earlier.

  104. This web site is really a walk-through for all of the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll definitely discover it.

  105. Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  106. I’d have to check with you here. Which is not something I usually do! I enjoy reading a post that will make people think. Also, thanks for allowing me to comment!

  107. Very interesting information!Perfect just what I was looking for!

  108. I think one of your advertisements triggered my internet browser to resize, you may want to put that on your blacklist.

  109. just beneath, are a lot of entirely not related web-sites to ours, even so, they may be surely really worth going over

  110. Thanks for some other fantastic post. Where else may just anyone get that type of info in such an ideal indicates of writing? I’ve a presentation next week, and I’m at the search for such info.

  111. the time to read or visit the material or web pages we’ve linked to below the

  112. Rather entertaining many many thanks, I believe your visitors could possibly want significantly more content similar to this carry on the great function.

Comments are closed.

%d bloggers like this: