【问题标题】:How to search in a folder by the name or extension of a file in winForm in C#?如何在 C# 中的 winForm 中通过文件的名称或扩展名在文件夹中搜索?
【发布时间】:2017-07-02 21:19:05
【问题描述】:

首先我们应该得到一个用户的目录。然后在指定的文件夹中,我们要按文件名或扩展名搜索文件。 例如,在该文件夹中,我们要搜索名称“Book”或 .txt 之类的扩展名。 假设我们有一个 Browse 按钮​​,通过单击它,我们可以获取路径并将其显示在标签中(在下面的代码中,它是 label1)。我们有一个搜索按钮和一个文本框,我们应该在文本框中输入名称或扩展名,然后单击搜索按钮,结果(创建的文件的名称)将显示在 MessageBox 中。
我写了一段只获取路径的代码,其余的我不知道怎么写。

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

【问题讨论】:

标签: c#


【解决方案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!");
            }
        }
    }

【讨论】:

    【解决方案2】:

    假设您的搜索按钮的点击事件使用以下函数

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

    【讨论】:

      猜你喜欢
      • 2020-04-16
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2010-12-21
      • 1970-01-01
      • 2018-02-07
      相关资源
      最近更新 更多