Good Morning Everyone,
I currently have a file copy routine that uses streams and updates the progress bar on my UI, this works fine in a thread when I do not await the thread to finish but as soon as I do (which is the behavior I want) I get an error about the process not being able to access the file being copied. The copy still continues and finishes if I press OK but I do not know why it is occurring? The way I want it to work is that if I am copying multiple files it will start a thread to copy one file, wait for it to finish and then continue the foreach loop to the next file? I am doing all this so that the UI is not blocked.
I currently have a file copy routine that uses streams and updates the progress bar on my UI, this works fine in a thread when I do not await the thread to finish but as soon as I do (which is the behavior I want) I get an error about the process not being able to access the file being copied. The copy still continues and finishes if I press OK but I do not know why it is occurring? The way I want it to work is that if I am copying multiple files it will start a thread to copy one file, wait for it to finish and then continue the foreach loop to the next file? I am doing all this so that the UI is not blocked.
frmMain.cs:
private async void CopyFiles()
{
TextBox TextBox = (TextBox)(frmMain_TabControl.SelectedTab.Controls.Find("frmMain_TabPage_page_txtAddress", true)[0]);
foreach (FileInfo file in m_FilesToCopy)
{
try
{
frmMain_ProgressBar.Visible = true;
frmMain_lblCopyingFile.Visible = true;
string source = file.FullName;
string destination = TextBox.Text + "\\" + file.Name;
WriteText("Copying File:" + file.Name);
await Task.Factory.StartNew(() => { CopyFile(source,destination); });
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
m_FilesToCopy.Clear();
}
#region Copy File routine
private void CopyFile(string source, string destination)
{
FileStream fsOut = new FileStream(destination, FileMode.Create); //error happens here
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756]; //1 MB
int readBytes;
while ((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
fsOut.Write(buffer, 0, readBytes);
frmMain_ProgressBar.Invoke(new Action(() =>
{
frmMain_ProgressBar.Value = (int)(fsIn.Position * 100 / fsIn.Length);
}));
}
}
#endregion