silverlight 如何获取服务器上的文件大小
/// <summary>
/// 文件块大小为4M ( 如果文件总大小超过 _chunkSize 定义的大小,则把该文件切割成大小为 _chunkSize 的文件块分批下载 )
/// </summary>
private int _chunkSize = 4 * 1024 * 1024;
/// <summary>
/// 已经下载的字节数
/// </summary>
private long _downloadedBytes = 0;
/// <summary>
/// 要下载的文件的总大小
/// </summary>
private long _length;
/// <summary>
/// 要下载的文件的地址
/// </summary>
public string Url = "http://localhost/Downloader/test.rar";
/// <summary>
/// 获取文件大小
/// </summary>
private void GetFileSize()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Url);
request.BeginGetResponse(result =>
{
HttpWebRequest req = (HttpWebRequest)result.AsyncState;
HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(result);
this._length = res.ContentLength;
}, request);
}
private void BeginRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Url);
request.Headers["Range"] = "bytes=" + this._downloadedBytes + "-" + (this._downloadedBytes + _chunkSize - 1);
request.BeginGetResponse(new AsyncCallback(ResponseCallBack), request);
}
private void ResponseCallBack(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
//this._lenght = response.ContentLength;// 这里获取的大小为当前请求的块大小
int count = 0;
using (System.IO.Stream stream = response.GetResponseStream())
{
string savaName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\test.rar";
System.IO.FileMode mode = this._downloadedBytes > 0 ? System.IO.FileMode.Append : System.IO.FileMode.CreateNew;
using (System.IO.FileStream fileStream = System.IO.File.Open(savaName, mode))
{
byte[] bytes = new byte[4096];
int read;
while ((read = stream.Read(bytes, 0, bytes.Length)) != 0)
{
fileStream.Write(bytes, 0, read);
count += read;
}
}
}
this._downloadedBytes += count;
if (_downloadedBytes < this._length)
{
this.BeginRequest();
}
}
request.Method = "HEAD";