用于ftp上传的ProgressBar

时间:2013-12-14 11:50:27

标签: c# ftp progress-bar

我有这个代码,我想添加一个进度条。请给我一些指导。我不知道从哪里开始编码。谢谢!

private void uploadbutton_Click(object sender, EventArgs e)
{
    try
    {
        openFileDialog1.ShowDialog();
        FileInfo feltoltfile = new FileInfo(openFileDialog1.FileName);
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpadress + "/" + feltoltfile.Name);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(textBox1.Text, textBox2.Text);
        StreamReader sourceStream = new StreamReader(feltoltfile.ToString());
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        serverstatus.Items.Add(response.StatusDescription +" "+feltoltfile.Name+ " --> " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
        response.Close();
        ftplista.Items.Clear();
        FTPlistalekerdezes(ftpadress, textBox1.Text, textBox2.Text);
        MessageBox.Show("Ready!");
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error!" + ex.Message);
    }    
}

1 个答案:

答案 0 :(得分:1)

未经测试的代码,但应该给你一个想法。我还使用了using语句:

openFileDialog1.ShowDialog();
FileInfo feltoltfile = new FileInfo(openFileDialog1.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpadress + "/" + feltoltfile.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(textBox1.Text, textBox2.Text);
using (var sourceStream = feltoltfile.OpenRead())
using (var requestStream = request.GetRequestStream())
{
    long fileSize = request.ContentLength = feltoltfile.Length;
    long bytesTransfered = 0;

    byte[] buffer = new byte[4096];
    int read;
    while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0) //while there are still bytes to be copied
    {
        requestStream.Write(buffer, 0, read);
        requestStream.Flush();
        bytesTransfered += read;
        //trigger progress event...
    }
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
    serverstatus.Items.Add(response.StatusDescription + " " + feltoltfile.Name + " --> " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
}
ftplista.Items.Clear();
FTPlistalekerdezes(ftpadress, textBox1.Text, textBox2.Text);
MessageBox.Show("Ready!");