我不明白我哪里错了。首先,我尝试使用Stream的长度,但会抛出“取消异常”。如果我尝试复制Stream例如stream.CopyTo(memoryStream),结果表明Stream是Disposed,而我无法读取它。像硬代码长度一样,只是要检查运行进度栏是否抛出此错误System.ArgumentOutOfRangeException:'200的值对于'Value'无效。 “值”应介于“最小值”和“最大值”之间。 参数名称:“值”。我仍然无所事事,需要做所有异步的事情。谁能帮忙。
private BackgroundWorker _worker;
public Form1()
{
InitializeComponent();
this._ftpInfo = new FtpInfo();
this._worker = new BackgroundWorker();
this._worker.WorkerSupportsCancellation = true;
this._worker.WorkerReportsProgress = true;
this._worker.ProgressChanged += backgroundWorker1_ProgressChanged;
this._worker.DoWork += backgroundWorker1_DoWork;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string result = Get_Data_From_Ftp_Server();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pb_Ftp.Value += e.ProgressPercentage;
lbl_Percents.Text = $"{pb_Ftp.Value.ToString()}%";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lbl_Percents.Text = "Complete!";
}
private string Get_Data_From_Ftp_Server()
{
//result data from file
string result = string.Empty;
//make request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(this._ftpInfo.Server + "/" + this._ftpInfo.FileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(this._ftpInfo.Username, this._ftpInfo.Password);
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(Path.Combine(this._ftpInfo.SaveDirectory, this._ftpInfo.FileName), FileMode.CreateNew, FileAccess.Write))
{
byte[] buffer = new byte[1024];
int byteRead = 0;
double read = 0;
do
{
byteRead = stream.Read(buffer, 0, 1024);
fs.Write(buffer, 0, byteRead);
read += (double)byteRead;
double percentage = read / 24 * 100;
_worker.ReportProgress((int)percentage);
}
while (byteRead != 0);
}
}
result = response.StatusDescription;
response.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message.ToString());
}
return result;
}
private void btn_Download_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
this._ftpInfo.SaveDirectory = dialog.SelectedPath;
this._ftpInfo.Server = text_Server.Text.Trim();
this._ftpInfo.FileName = text_Ftp_FileName.Text.Trim();
this._ftpInfo.Username = text_Username.Text.Trim();
this._ftpInfo.Password = text_Password.Text.Trim();
this._worker.RunWorkerAsync();
}
private static void Check_Directory(string directory)
{
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
}
}