简体   繁体   中英

File searching with c#

I want to search all the folders of the selected disk for the file the user has entered. If the file is directly on the disk, I get a return but it doesn't inspect subfolders.

string arama = TextBox1.Text;
string yol = ListBox1.SelectedItem.Value;

if (File.Exists(yol + arama))
{
    string[] files = Directory.GetFiles(yol, arama);
    foreach (string file in files)
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA VAR. DOSYA YOLU = " + file + "');", true);
}
else
{
    try
    {
        string[] files2 = Directory.GetFiles(yol, arama, SearchOption.AllDirectories);
        if (files2 == null)
            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA YOK" + "');", true);
        else
            foreach (string file in files2)
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA VAR. YOLU:" + files2 + "');", true);
    }
    catch (Exception ex)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA VAR. YOLU:" + ex + "');", true);
    }
}

It seems you need to add SearchOption.AllDirectories if file exists.

Includes the current directory and all its subdirectories in a search operation. This option includes reparse points such as mounted drives and symbolic links in the search.

So, this

if (File.Exists(yol + arama))
{
    string[] files = Directory.GetFiles(yol, arama);
    foreach (string file in files)
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA VAR. DOSYA YOLU = " + file + "');", true);
}

should be:

if (File.Exists(yol + arama))
{
    string[] files = Directory.GetFiles(yol, arama, SearchOption.AllDirectories);
    foreach (string file in files)
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "DOSYA VAR. DOSYA YOLU = " + file + "');", true);
}

See: GetFiles(String, String, SearchOption)

You can search all subfolders with this code;

private void ListFiles(DirectoryInfo dr, string searchname)
{
    System.IO.FileInfo[] files = null;
    System.IO.DirectoryInfo[] subDirs = null;
    try
    {
        files = dr.GetFiles(searchname + ".*");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    if (files != null)
    {
        foreach (FileInfo fi in files)
        {
            allFiles.Add(fi);
        }
        subDirs = dr.GetDirectories();

        foreach (DirectoryInfo di in subDirs)
        {
            ListFiles(di, searchname);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM