2017-07-01 127 views
0

首先我们应该得到用户的一个目录。然后在指定的文件夹中,我们要通过名称或其扩展名搜索文件。 例如在该文件夹中我们要搜索名称“Book”或像.txt这样的扩展名。 假设我们有一个浏览按钮,并通过点击它,我们得到的路径,并显示在一个标签(在下面的代码中它是label1)。我们有一个搜索按钮和一个文本框,我们应该在文本框中写入名称或扩展名,并通过单击搜索按钮将结果(创建的文件的名称)显示在MessageBox中。
我写了一段代码,只获取路径,我不知道如何写剩下的代码。如何在C#中用winForm中的文件的名称或扩展名搜索文件夹?

private void Browse_Click(object sender, EventArgs e) 
{ 
    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) 
    { 
     this.label1.Text = folderBrowserDialog1.SelectedPath; 
     Directory = label1.ToString(); 
    } 
} 
+2

您正在寻找[System.IO .Directory.GetFiles()](https://msdn.microsoft.com/en-us/library/wz42302f(v = vs.110)的.aspx)... –

回答

1

下面是使用Directory.GetFiles()与搜索模式的一个简单的例子:

private void Browse_Click(object sender, EventArgs e) 
    { 
     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) 
     { 
      string[] matches = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*book*"); // use "*.txt" to find all text files 
      if (matches.Length > 0) 
      { 
       foreach (string file in matches) 
       { 
        Console.WriteLine(file); 
       } 
      } 
      else 
      { 
       MessageBox.Show("No matches found!"); 
      } 
     } 
    } 
0

假设你的搜索按钮的单击事件使用下面的函数

private void Search_Click(object sender, EventArgs e) 
{ 
    DirectoryInfo Di=new DirectoryInfo(label1.Text); 
    foreach(FileInfo fi in Di.GetFiles()) 
    { 
     textbox.Text+=fi.Name+"\r\n"; 
    } 
} 
相关问题