0

I want to add a textbox to a program which lists files in given path. It will show current searching directory on a panel. even if I added textvox1.Text = dir like this, It only shows last directory at the end of the search. Can you tell me why it doesn't work? Related question

public void GetFiles(string dir)
{
    textBox1.Text = dir;
    string[] filetypes = new string[] { "cfg", "txt" };
    foreach (string ft in filetypes)
    {                
        foreach (string file in Directory.GetFiles(dir, string.Format("*.{0}", ft), SearchOption.TopDirectoryOnly))
        {                   
            files.Add(new FileInfo(file));
        }                
    }
    foreach (string subDir in Directory.GetDirectories(dir))
    {                
        try
        {                    
            GetFiles(subDir);
        }                    
        catch
        {
        }            
    }
}
Community
  • 1
  • 1
emmett
  • 193
  • 2
  • 14
  • you are overwriting the text in the textbox so quickly you only see the last one, in reality (I assume but your code flow is strange) they are all being set to the textboxes text – Sayse Oct 03 '13 at 12:20
  • Try refresh the textbox every time. – Alessandro D'Andria Oct 03 '13 at 12:26
  • shouldnt it work replacing textbox1.text with "if (textBox1.Text != dir.ToString()) textBox1.Text.Replace(textBox1.Text, dir.ToString()); else textBox1.Text = dir.ToString();" ? – emmett Oct 03 '13 at 12:51

1 Answers1

0

The "quick fix" is to call DoEvents() after setting the TextBox:

textBox1.Text = dir;
Application.DoEvents();
// ... rest of the code ...

The proper fix, however, is to place that code into a background thread. If you use the BackgroundWorker() control you can use ReportProgress() and the associated ProgressChanged() event to update the TextBox.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Thanks. It works fine. But, how about adding this, does it slow the process? "public void currentdir(FileInfo info) { textBox1.Text = info.FullName; } public void textBox1_TextChanged(object sender, EventArgs e) { try {currentdir(new FileInfo(dir)); } catch{} }" – emmett Oct 03 '13 at 13:23
  • Technically it does slow down the process. If you don't want it to be slower then either don't provide feedback to the user, or provide less feedback. Do they really need to see every single folder? Chances are they will fly by so fast that they can't even be understood anyways... – Idle_Mind Oct 03 '13 at 13:58