C# 在后台工作人员查询中打开目录并处理文件/文件夹

C# 在后台工作人员查询中打开目录并处理文件/文件夹,c#,filepath,C#,Filepath,我有下面的代码,我试图打开一个目录,并通过后台工作程序处理其中的文件,但我遇到了问题 我的错误是(名称filePath在当前上下文中不存在),我可以理解,因为它存储在另一个方法中?如果有人能指出我的代码有什么问题,我们将不胜感激。Folderbrowser在后台工作区下不工作 private void btnFiles_Click(object sender, EventArgs e) { //btnFiles.Enabled = false; btnST

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

我的错误是(名称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);
        }
变量“filePath”被声明为btnFiles\u Click方法的本地变量。为了在其他地方使用,必须在代码页中将其声明为全局:

public class Form1
{
    private String _filePath = null;

    private void btnFiles_Click(object sender, EventArgs e)
    {
        //get your file and assign _filePath here...
        _filePath = folderBrowserDialog1.SelectedPath;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //use _filePath here...
    }
}
变量“filePath”被声明为btnFiles\u Click方法的本地变量。为了在其他地方使用,必须在代码页中将其声明为全局:

public class Form1
{
    private String _filePath = null;

    private void btnFiles_Click(object sender, EventArgs e)
    {
        //get your file and assign _filePath here...
        _filePath = folderBrowserDialog1.SelectedPath;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //use _filePath here...
    }
}

@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;
    ...
}

@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;
    ...
}

谢谢Don,明白了。请注意,就BackgroundWorker线程所知,\u filePath变量在理论上可能保持未初始化状态。如果您希望在线程之间共享变量,则应使用同步形式(例如lock语句)对其进行保护,或将其声明为“volatile”。即使在x86上(数据访问总是不稳定的),您也不想冒一些编译器优化的风险,而在其他平台(如ARM)上运行.NET(取决于平台特定的行为)是个坏主意。谢谢don,注意,就BackgroundWorker线程所知,_filePath变量在理论上可能保持未初始化状态。如果您希望在线程之间共享变量,则应使用同步形式(例如lock语句)对其进行保护,或将其声明为“volatile”。即使在x86上(数据访问总是易变的语义),您也不想冒一些编译器优化的风险,而在其他平台(如ARM)上运行.NET取决于平台特定的行为是个坏主意。感谢您的示例SinatrIMHO,这实际上是更好的解决方案,由于它避免了跨线程同步问题(请参阅我在另一个答案中的评论)。至少在传递值类型和不可变引用类型对象(如字符串)时,可以完全避免跨线程同步问题。感谢您的示例SinatrIMHO,这实际上是更好的解决方案,因为它避免了跨线程同步问题(请参阅另一个答案中我的注释)。至少在传递值类型和不可变引用类型对象(如字符串)时,可以完全避免跨线程同步问题。