简体   繁体   中英

how do I take information from one private void and put it in another

i want to take information from one private void and then put it into another I need to do this and cannot run them in the same section because I have been told that wont work with what i want the code to do. here is the code that isn't working its the dlg2.selectedPath that inst being recognised from the button private void where it needs to be.

    private void button1_Click(object sender, EventArgs e)
    {
       FolderBrowserDialog dlg2 = new FolderBrowserDialog();
        if (dlg2.ShowDialog() == DialogResult.OK)
        //do whatever with dlg.SelectedPath
        {
            backgroundWorker1.RunWorkerAsync();
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

            DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
            DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);

            DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
            FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
            foreach (FileInfo fi in fis)
            {
                if (fi.LastWriteTime.Date == DateTime.Today.Date)
                {
                    File.Copy(fi.FullName, target.FullName + "\\" + fi.Name, true);
                }
            }

        }

any help will be appreciated.

You can call backgroundWorker1.RunWorkerAsync(dlg2.SelectedPath) . That will pass the string to the worker. In your DoWork handler, you can get the value from the DoWorkEventArgs instance:

string selectedPath = (string)e.Argument;
DirectoryInfo target = new DirectoryInfo(selectedPath);

The background worker can't acess the dlg2.SelectedPath bacause it works in another thread. the dlg2 it's in the UI thread, the backgroundWorker, is in an other .net created thread. You must use Control.Invoke, and the Control.InvokeRequired to make it work.

SEE

Control Invoke

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