Skip to main content
 首页 » 编程设计

c#之在后台 worker 查询中打开一个目录并处理文件/文件夹

2024年02月06日13thcjp

我有以下代码,我试图打开一个目录并通过后台工作程序处理其中的文件,但我遇到了问题。

我遇到的错误是(名称 filePath 在当前上下文中不存在),我可以理解,因为它存储在另一个方法中?如果有人可以向我指出我的代码有什么问题,我们将不胜感激。 Folderbrowser 在后台工作部分下不起作用。

private void btnFiles_Click(object sender, EventArgs e) 
    { 
        //btnFiles.Enabled = false; 
        btnSTOP.Enabled = true; 
        //Clear text fields 
        listBoxResults.Items.Clear(); 
        listBoxPath.Items.Clear(); 
        txtItemsFound.Text = String.Empty; 
        //Open folder browser for user to select the folder to scan 
        DialogResult result = folderBrowserDialog1.ShowDialog(); 
        if (result == DialogResult.OK) 
        { 
            //Store selected folder path 
            string filePath = folderBrowserDialog1.SelectedPath; 
        } 
        //Start the async operation here 
        backgroundWorker1.RunWorkerAsync(); 
    } 
 
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
        //Process the folder 
            try 
            { 
                foreach (string dir in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(filePath, "*.*", SearchOption.AllDirectories, true)) 
                { 
                    //Populate List Box with all files found 
                    this.Invoke(new Action(() => listUpdate2(dir))); 
                    FileInfo fi = new FileInfo(dir); 
                    if (fi.Length == 0) 
                    { 
                        //Populate List Box with all empty files found 
                        this.Invoke(new Action(() => listUpdate1(dir + Environment.NewLine))); 
                    } 
                } 
            } 
 
            //Catch exceptions 
            catch (Exception err) 
            { 
                // This code just writes out the message and continues to recurse.  
                log.Add(err.Message); 
                //throw; 
            } 
            finally 
            { 
                //add a count of the empty files here 
                txtItemsFound.Text = listBoxResults.Items.Count.ToString(); 
 
                // Write out all the files that could not be processed. 
                foreach (string s in log) 
                { 
                    this.Invoke(new Action(() => listUpdate1(s))); 
                } 
                log.Clear(); 
                MessageBox.Show("Scanning Complete", "Done", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
            } 
            //If cancel button was pressed while the execution is in progress 
            //Change the state from cancellation ---> cancelled 
            if (backgroundWorker1.CancellationPending) 
            { 
                e.Cancel = true; 
                //backgroundWorker1.ReportProgress(0); 
                return; 
            } 
            //} 
            //Report 100% completion on operation completed 
            backgroundWorker1.ReportProgress(100); 
        } 

请您参考如下方法:

@DonBoitnott 解决方案是类内数据流最通用的解决方案。具体到 BackgroundWorker 还有一个存在

private void btnFiles_Click(object sender, EventArgs e) 
{ 
    ... 
    // pass folder name 
    backgroundWorker1.RunWorkerAsync(folderBrowserDialog1.SelectedPath); 
} 
 
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // get passed folder name 
    string filePath = (string)e.Argument; 
    ... 
}