开发者

How to display all the text files that are in the local system to a list box on From Load

开发者 https://www.devze.com 2023-02-21 00:52 出处:网络
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 o开发者_Python百科ne help me.

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 o开发者_Python百科ne 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


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;


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消