i am trying to upload on ftp, using UploadFileAsync method, i need to update a progress bar this is why i maked it asynchronously but i also want to wait until the upload complets then i continu processing there is what i am doing , but it want works, i tried also with Task.RunSynchronously() ... for Uploading :
private async Task<Hashtable> UploadFile(FileSended file , string folder)
{
bool isUploaded = true;
string fileName = file.FileName;
string msg = "";
data = new Hashtable();
try
{
completed = false;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(UserId, Password);
Uri siteUri = new Uri(Host + "/" + folder + "/" + fileName);
client.UploadFileCompleted += WebClientUploadCompleted;
client.UploadProgressChanged += WebClientUploadProgressChanged;
await Task.Run(() => UploadToFtp(client, siteUri,file.LocalPath)) ;
}
for (int i = 0; i < ProgressFtp.Count; i++)
{
parentForm.progressBar.Value = ProgressFtp[i];
parentForm.lbStatus.Text = "Progress : " + parentForm.progressBar.Value + "%";
parentForm.lbStatus.Refresh();
}
msg = "OK";
}
catch (Exception e)
{
isUploaded = false;
}
data.Add("IsUploaded", isUploaded);
data.Add("Message", msg);
return data;
}
the method :
private static bool UploadToFtp(WebClient client, Uri uri, string localPath)
{
bool uploaded = true;
try
{
client.UploadFileAsync(uri, WebRequestMethods.Ftp.UploadFile, file.LocalPath);
}
catch (Exception e)
{
Message = e.Message;
uploaded = false;
}
return uploaded;
}
WebClientUploadProgressChanged :
private static void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressFtp.Add(e.ProgressPercentage);
}
ProgressFTP is a int list that i use to update the progressBar , because when i do it on WebClientUploadProgressChanged , it cause an exception :
cross thread operation not valid
so i gone around it .