// 同步下载文件 public static byte[] downloadFile(string url, int offset = 0, byte[] helperBytes = null, string fileName = "", StartDownloadCallback startCallback = null, DownloadingCallback downloading = null) { logInfo("开始http下载:" + url, LOG_LEVEL.LL_FORCE); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.AddRange(offset); WebResponse response = request.GetResponse(); long fileSize = response.ContentLength + offset; // response.ContentLength只是剩余需要下载的长度,需要加上下载起始偏移才是文件的真实大小 startCallback?.Invoke(fileName, fileSize); Stream inStream = response.GetResponseStream();// 获取http MemoryStream downloadStream = new MemoryStream(); if(helperBytes == null) { helperBytes = new byte[1024]; } int readCount; do { // 从输入流中读取数据放入内存中 readCount = inStream.Read(helperBytes, 0, helperBytes.Length);// 读流 downloadStream.Write(helperBytes, 0, readCount);// 写流 downloading?.Invoke(fileName, fileSize, downloadStream.Length); } while (readCount > 0); byte[] dataBytes = downloadStream.ToArray(); downloadStream.Close(); inStream.Close(); response.Close(); logInfo("http下载完成:" + url, LOG_LEVEL.LL_FORCE); return dataBytes; }
public void download(string fullURL, string fileName, long offset, DownloadingCallback downloading, TimeoutCallback timeout, StartCallback start, FinishCallback finish) { mDownloadListLock.waitForUnlock(); DownloadInfo info = new DownloadInfo(); // 下载地址里需要将空格替换为%20 info.mURL = StringUtility.strReplaceAll(fullURL, " ", "%20"); info.mFileName = fileName; info.mDownloadingCallback = downloading; info.mStartCallback = start; info.mFinishCallback = finish; info.mTimeoutCallback = timeout; info.mDownloadOffset = offset; mDownloadList.Add(info); mDownloadListLock.unlock(); }