1.Stream 转换为 MemoryStream(Stream不支持查找)
MemoryStream StreamToMemoryStream(Stream instream) { MemoryStream outstream = new MemoryStream(); const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = instream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } return outstream; }
2.网络流转化为内存流并下载
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath); request.Method = "GET"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { Stream rs = response.GetResponseStream(); //网络流转换为内存流 var ms = StreamToMemoryStream(rs); ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream byte[] bytes = new byte[buffsize]; ms.Read(bytes, 0, buffsize); ms.Flush(); ms.Close(); rs.Flush(); rs.Close(); //以文件流的方式下载 Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.ContentType = "application/octet-stream"; if (HttpContext.Current.Request.UserAgent.ToUpper().Contains("MSIE") || HttpContext.Current.Request.UserAgent.ToUpper().Contains("TRIDENT") || HttpContext.Current.Request.UserAgent.ToUpper().Contains("EDGE")) { name = HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8); } else { name = name.Replace(" ", "_"); } //fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); Response.AddHeader("Content-Disposition", "attachment; filename=" + name); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } }
3.网络路径
private string GetContractPathRules(string id, string name) { string url = ConfigurationManager.AppSettings["ContractUrl"]; url = url.TrimEnd('/') + "/"; return Path.Combine(url, Path.Combine(id + "/", name)); } //例如:http://x.x.x.x:8088/xxx/xxx.pdf