问题
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.
回答1:
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);
回答2:
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
来源:https://stackoverflow.com/questions/4899740/how-do-i-take-information-from-one-private-void-and-put-it-in-another