如何将本地系统中的所有文本文件显示到“从加载”列表框中

发布于 2024-10-28 03:49:16 字数 240 浏览 3 评论 0原文

我的表单上有一个列表框,我需要的是我想将本地驱动器中显示的所有文本文件显示到表单加载上的该列表框中,任何人都可以帮助我。

我这样写了我的代码

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

但这引发了一个错误我如何从所有目录中读取文件

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千纸鹤带着心事 2024-11-04 03:49:16

像这样的事情:

string drivePath = @"C:\";

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

请注意,整个驱动器的递归遍历可能需要很长时间...

编辑:

为了避免访问被拒绝问题,而不是Directory.GetFiles()您可以使用此中给出的代码答案

string drivePath = @"C:\";

var textFiles = GetFiles(drivePath, "*.txt").ToList();
listBox1.DataSource = textFiles;

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;
可遇━不可求 2024-11-04 03:49:16

扫描文件系统是递归的一个例子,有很多例子。但是,“加载时”执行此操作会减慢表单加载速度,您应该做的是加载表单,然后在其关闭时生成“正在填充表单”显示,毕竟,如果需要 10 分钟来扫描您不希望您的用户假设您的系统崩溃了。

查找文本文件的代码示例如下:

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);
  }
}

确保以某种形式的线程运行此代码,以便您的应用程序可以保持响应。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文