Question

I am trying to add a progress bar to my uploadbutton. i am sending a xmldocument file to a server. i have already looked at seaveral ansers but i can not find a correct solution for the way i send my file. this is my current code. i have tryed a backgroundworker but i get a exception that the thread i use to get the response is not the correct thread so i was wondering if somebody hire has a easy way to do this with the code below

 private  void btnHttpPost_Click(object sender, EventArgs e)
    {
        WebRequest request;

        if (string.IsNullOrEmpty(txtPassword.Text) && string.IsNullOrEmpty(txtUsername.Text))
            request = WebRequest.Create(txtHttpPost.Text.Trim());
        else
            request = WebRequest.Create(txtHttpPost.Text.Trim() + "&" + txtUsername.Text.Trim() + "&" + txtPassword.Text.Trim());

        request.Method = "POST";
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(_original.InnerXml);
        request.ContentType = "binary/octet-stream";
        request.ContentLength = bytes.Length;                  
        Stream dataStream = request.GetRequestStream();;
        dataStream.Write(bytes, 0, bytes.Length);
        dataStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
        dataStream = response.GetResponseStream();
        if (dataStream != null)
        {
            var reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            txtResponse.Text += responseFromServer;
            // Clean up the streams.
            reader.Close();
        }
        if (dataStream != null) dataStream.Close();
        response.Close();
    }

can anybody help me? thanks in advance

Was it helpful?

Solution

You send your data as one block:

dataStream.Write(bytes, 0, bytes.Length);

You should send your data in chunks (small parts of several hundred bytes) and update the progress bar after each chunk.

Pseudocode:

int dataavail = bytes.Length;
int chunkSize = 512; // 1024, 2048, 4096 are good too
while( dataavail > 0 )
{

  dataStream.Write(bytes, bytes.Length - dataavail , Math.Min(chunkSize, dataavail));
  dataavail -= chunkSize;

  // TODO: Update Progress Indicator here

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top