我在c#中有这个简单的代码,它可以找到所有目标目录及其子文件夹,但是我的处理时我无法与GUI形式交互,我应该使用BackgroundWorker如何用这段代码实现:
var dir = textBox1.Text = folderBrowserDialog1.SelectedPath;
textBox2.Text="";
string[] extensions = { ".htm", ".html" };
var files = Directory.EnumerateFiles(dir, "*.*",SearchOption.AllDirectories)
.Where(s => s.EndsWith(".html") || s.EndsWith(".htm")).OrderBy(f => f);
foreach (string file in files)
{ System.Diagnostics.Debug.WriteLine(file);
textBox2.AppendText(file+Environment.NewLine);
}
答案 0 :(得分:0)
您是否阅读过此链接?注意从其他线程更新gui(使用BackgroundWorker,这通常在ProgressChanged事件处理程序中完成:https://msdn.microsoft.com/en-us/library/3s8xdz5c(v=vs.110).aspx
答案 1 :(得分:0)
从不介意我找到了解决方案:
void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
string[] extensions = { ".htm", ".html" };
var files = Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".html") || s.EndsWith(".htm")).OrderBy(f => f);
foreach (string file in files)
{
Thread.Sleep(5);
System.Diagnostics.Debug.WriteLine(file);
backgroundWorker1.ReportProgress(0,file+Environment.NewLine);
}
}
void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox2.AppendText(e.UserState as string);
}