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

发布于 2024-11-01 08:26:34 字数 1549 浏览 0 评论 0原文

我从 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
            }

请帮助我。谢谢。

I call a method from web service to get a binary data. The data's size is more big. How to get the percent of downloading data from web service? I use BackgroundWorker thread to get data asynchorously.

Thanks.

Update: This is the method from my web service

[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;
        }

This method will return a binary file. And my codes to get data from this method in WinForm application:

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
            }

Please help me. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美煞众生 2024-11-08 08:26:34

您可以使用 soap 扩展来执行此操作。

You can use soap extensions to do this.

故事和酒 2024-11-08 08:26:34

这不会构建,但应该给你这个想法:
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
        }
    }

This won't build but should give you the idea:
webResponse.ContentLength; will give total size assuming the server sends it.
Current progress can be kept track of. Use a delegate to update status in a ui thread.

    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
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文