/// <summary> /// 下载媒体文件。 /// 如果下载成功,返回值的ErrMsg属性携带保存的文件全路径 /// </summary> /// <param name="mediaId"></param> /// <param name="filePath"> /// 保存下载的文件的本地文件名或目录(以\结尾)。 /// 如果为目录,则文件名为微信响应的文件名。 /// 如果文件已经存在,则会覆盖原文件。 /// </param> /// <returns>如果成功,ErrMsg属性携带保存的文件全路径</returns> public BasicResult Download(string mediaId, string filePath) { var param = new FormData { { "access_token", AccessToken }, { "media_id", mediaId } }; var url = string.Format("{0}?{1}", DownLoadUrl, param.Format()); var request = HttpHelper.CreateRequest(url); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { var disposition = response.Headers["Content-disposition"]; if (string.IsNullOrEmpty(disposition)) { var s = new StreamReader(stream, Encoding.UTF8).ReadToEnd(); return(JsonConvert.DeserializeObject <BasicResult>(s)); } filePath = filePath.EndsWith(@"\") ? string.Format("{0}{1}", filePath, Regex.Match(disposition, "(?<=filename\\s*=\\s*\\\"?)[^\\\"]+", RegexOptions.IgnoreCase)) : filePath; var fs = new FileStream(filePath, FileMode.OpenOrCreate); try { var buffer = new byte[128 * 1024]; //128K int i; while ((i = stream.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, i); } return(BasicResult.GetSuccess(filePath)); } finally { fs.Close(); } } }
/// <summary> /// 下载媒体文件。 /// 如果下载成功,返回值的ErrMsg属性携带保存的文件全路径 /// </summary> /// <param name="mediaId"></param> /// <param name="filePath"> /// 保存下载的文件的本地文件名或目录(以\结尾)。 /// 如果为目录,则文件名为微信响应的文件名。 /// 如果文件已经存在,则会覆盖原文件。 /// </param> /// <returns>如果成功,ErrMsg属性携带保存的文件全路径</returns> public BasicResult Download(string mediaId, string filePath) { var param = new FormData { {"access_token", AccessToken}, {"media_id", mediaId} }; var url = string.Format("{0}?{1}", DownLoadUrl, param.Format()); var request = HttpHelper.CreateRequest(url); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { var disposition = response.Headers["Content-disposition"]; if (string.IsNullOrEmpty(disposition)) { var s = new StreamReader(stream, Encoding.UTF8).ReadToEnd(); return JsonConvert.DeserializeObject<BasicResult>(s); } filePath = filePath.EndsWith(@"\") ? string.Format("{0}{1}", filePath, Regex.Match(disposition, "(?<=filename\\s*=\\s*\\\"?)[^\\\"]+", RegexOptions.IgnoreCase)) : filePath; var fs = new FileStream(filePath, FileMode.OpenOrCreate); try { var buffer = new byte[128*1024]; //128K int i; while ((i = stream.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, i); } return BasicResult.GetSuccess(filePath); } finally { fs.Close(); } } }