My code works, but the ProgressBar
jumps directly to 100% and the download will go on. When its finished then comes a messageBox to take a Info.
I have already changed the buffer size, but it doesn't matter.
What am I doing wrong here?
Here is my Code:
void workerDOWN_DoWork(object sender, DoWorkEventArgs e)
{
string fileFullPath = e.Argument as String;
string fileName = Path.GetFileName(fileFullPath);
string fileExtension = Path.GetExtension(fileName);
label4.Invoke((MethodInvoker)delegate { label4.Text = "Downloading File.."; });
string ftpServerIP = "XXX";
string ftpUserName = "XXX";
string ftpPassword = "XXX";
try
{
//Datei vom FTP Server downloaden
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(fileFullPath))
{
var buffer = new byte[32 * 1024];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
var progress = (int)((float)totalReadBytesCount / (float)fileStream.Length * 100);
workerDOWN.ReportProgress((int)progress);
label3.Invoke((MethodInvoker)delegate { label3.Text = progress + " %"; });
}
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
MessageBox.Show("Datei nicht gefunden!", "Error");
}
}
e.Result = fileFullPath;
}
void workerDOWN_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string fileFullPath = e.Result as String;
string fileName = Path.GetFileName(fileFullPath);
MessageBox.Show("Download erfolgreich!","Information");
progressBar1.Value = 0;
label3.Invoke((MethodInvoker)delegate { label3.Text = " "; });
label4.Invoke((MethodInvoker)delegate { label4.Text = " "; });
}