0

I am having a list box on my form what i need is i would like to display all the text files that are presented in the local drives to that list box on Form Load can any one help me.

I wrote my code like this

string[] filepaths;
filepaths = Directory.GetFiles(@"c:\", "*.txt", SearchOption.AllDirectories);

But this is throwing an error how can i read the files from all directories

Developer
  • 8,390
  • 41
  • 129
  • 238

3 Answers3

2

Something like this:

string drivePath = @"C:\";

var textFiles = Directory.GetFiles(drivePath, "*.txt", SearchOption.AllDirectories);
listBox1.DataSource = textFiles;

notice that a recursive walk of an entire drive can take a long time...

EDIT:

To avoid access denied problem, instead of Directory.GetFiles() you can use the code given in this answer :

string drivePath = @"C:\";

var textFiles = GetFiles(drivePath, "*.txt").ToList();
listBox1.DataSource = textFiles;
Community
  • 1
  • 1
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • This is throwing an error as Access to the path 'c:\System Volume Information' is denied. – Developer Apr 01 '11 at 09:09
  • But i would like to get the files from all the directories – Developer Apr 01 '11 at 09:20
  • @Dorababu: you can't access to "System Volume information" folder (and there's no point in accessing it IMHO). BTW, have a look at this (xp related) [link](http://support.microsoft.com/kb/309531/en-us) – digEmAll Apr 01 '11 at 09:26
0

This method should do what you want: http://msdn.microsoft.com/en-us/library/wz42302f.aspx

DaveRead
  • 3,371
  • 1
  • 21
  • 24
0

Scanning through your file system, is a case of recursion, many examples are out there. However, to do it "on load" will slow down the form loading, what you should do, is load the form, and then produce a "populating form" display while it goes off, after all, if it take 10 minutes to scan you dont want your users assuming your systems crashed.

An example of the code to find your text files would be such as:

List<String> files=new List<string>();

void Walk(String  name)
{
  For each (String sFileName in Directory.Getfiles(name,"*.txt"))
  {
      files.add(sFilename);
  }
  For each (String sDirectory in Directory.GetDirectories(name))
  {
    Walk(sDirectory);
  }
}

Make sure you run this in some form of thread so your app can remain responsive.

BugFinder
  • 17,474
  • 4
  • 36
  • 51