文件流与内存流存储
1.文件流放入指定路径
//string retString = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = contentType; request.Accept = "*/*"; request.Headers.Add("SERVICE-AUTHENTICATION", authorization); byte[] bt = Encoding.UTF8.GetBytes(param); string responseData = String.Empty; request.ContentLength = bt.Length; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bt, 0, bt.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream steam = response.GetResponseStream()) { string path = HttpContext.Current.Server.MapPath("/")+"Temp\\"; string fileName = "名称" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";//客户端保存的文件名 filePath = path + "\\" + fileName;//路径 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { int size = 2048; byte[] data = new byte[response.ContentLength]; while (true) { size = steam.Read(data, 0, data.Length); if (size > 0) { fileStream.Write(data, 0, size); } else { break; } } } } }
2.内存流将文件放入本地路径
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = contentType; request.Headers.Add("SERVICE-AUTHENTICATION", authorization); byte[] bt = Encoding.UTF8.GetBytes(param); string responseData = String.Empty; request.ContentLength = bt.Length; request.UserAgent = "Code Sample Web Client"; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bt, 0, bt.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { byte[] data; using (var mstrm = new MemoryStream()) { using (var s = response.GetResponseStream()) { var tempBuffer = new byte[4096]; int bytesRead; while ((bytesRead = s.Read(tempBuffer, 0, tempBuffer.Length)) != 0) { mstrm.Write(tempBuffer, 0, bytesRead); } } mstrm.Flush(); data = mstrm.GetBuffer(); } MemoryStream memorystream = new MemoryStream(data); using (Stream steam = memorystream) { string path = HttpContext.Current.Server.MapPath(" / ") + "Temp\\"; string fileName = "名称" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";//客户端保存的文件名 filePath = path + "\\" + fileName;//路径 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { int size = 2048; while (true) { size = steam.Read(data, 0, data.Length); if (size > 0) { fileStream.Write(data, 0, size); } else { break; } } } } }