Hi there I am a C# student. On C# Windows Forms.
I am trying to copy directories async when clicking a button and having a label that shows the file being copied.
I get the following error:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.'
This is my code:
private void CopyDirectoriesAsync(string sourcePath, string destPath)
{
DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); }
foreach (FileInfo file in sourceDirectory.GetFiles())
{
label1.Text = file.FullName;
File.Copy(file.FullName, Path.Combine(destPath, file.Name), true);
}
foreach (DirectoryInfo sourceSubDir in sourceDirectory.GetDirectories())
{
CopyDirectoriesAsync(sourceSubDir.FullName, Path.Combine(destPath, sourceSubDir.Name));
}
}
private async void button1_Click(object sender, EventArgs e)
{
await Task.Run(()=> CopyDirectoriesAsync(@"C:\Users\afernandez.b\1", @"C:\Users\afernandez.b\2"));
label1.Text = "Finish";
}
Can someone please help me? I've done a lot of research but I have some issue to understand the answers given in other posts.
Thank you very much for your help