如何计算从网络服务下载数据的百分比
我从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 soap 扩展来执行此操作。
You can use soap extensions to do this.
这不会构建,但应该给你这个想法:
webResponse.ContentLength;假设服务器发送它,将给出总大小。
可以跟踪当前的进度。使用委托来更新 ui 线程中的状态。
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.