如何计算从Web服务下载数据的百分比

时间:2011-04-14 02:24:16

标签: c# multithreading web-services

我从Web服务调用一个方法来获取二进制数据。数据的大小更大。如何获得从Web服务下载数据的百分比?我使用BackgroundWorker线程异步获取数据。

感谢。

更新:这是我的网络服务

的方法
[WebMethod]
        public byte[] Data()
        {
            byte[] buffer;
            string filePath = Server.MapPath("Services.rar");
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;  // sum is a buffer offset for next reading
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }

此方法将返回二进制文件。以及我在WinForm应用程序中从此方法获取数据的代码:

private void button1_Click(object sender, EventArgs e)
        {
            localhost.Service1 service = new localhost.Service1();
            byte[] data = service.Data();
// where I get data, time to finish getting data depended on file's size.
// I want to calculate the time to finish and display percentage
            }

请帮帮我。感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用soap extensions执行此操作。

答案 1 :(得分:0)

这不会构建,但应该给你的想法: webResponse.ContentLength;假定服务器发送它将给出总大小。 目前的进展可以跟踪。使用委托更新ui线程中的状态。

    private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);

    private void Download(string url, string localPath)
    {
        using (WebClient wcDownload = new WebClient())
        {
            try
            {
                // Create a request to the file we are downloading
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                // Set default authentication for retrieving the file
                webRequest.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve the response from the server
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                // Ask the server for the file size and store it
                Int64 fileSize = webResponse.ContentLength;

                // Open the URL for download 
                strResponse = wcDownload.OpenRead(txtUrl.Text);
                // Create a new file stream where we will be saving the data (local drive)
                strLocal = new FileStream(string localPath, FileMode.Create, FileAccess.Write, FileShare.None);

                // It will store the current number of bytes we retrieved from the server
                int bytesSize = 0;
                // A buffer for storing and writing the data retrieved from the server
                byte[] downBuffer = new byte[2048];

                // Loop through the buffer until the buffer is empty
                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    // Write the data from the buffer to the local hard drive
                    strLocal.Write(downBuffer, 0, bytesSize);
                    // Invoke the method that updates the form's label and progress bar
                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
                }
            }
            finally
            {
                // When the above code has ended, close the streams
                strResponse.Close();
                strLocal.Close();
            }
        }

    private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
    {
        // Calculate the download progress in percentages
        PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
        // Make progress on the progress bar
        prgDownload.Value = PercentProgress;
        // Display the current progress on the form
        lblProgress.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)";

        if (BytesRead == TotalBytes)
        {
        //done
        }
    }