private void GetFileFromNetUrl(string url) { try { System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "GET"; //获得用户名密码的Base64编码 添加Authorization到HTTP头 不需要的账号密码的可以注释下面两行代码 string code = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "userName", "passWord"))); req.Headers.Add("Authorization", "Basic " + code); byte[] fileBytes; using (WebResponse webRes = req.GetResponse()) { int length = (int)webRes.ContentLength; HttpWebResponse response = webRes as HttpWebResponse; Stream stream = response.GetResponseStream(); //读取到内存 MemoryStream stmMemory = new MemoryStream(); byte[] buffer = new byte[length]; int i; //将字节逐个放入到Byte中 while ((i = stream.Read(buffer, 0, buffer.Length)) > 0) { stmMemory.Write(buffer, 0, i); } fileBytes = stmMemory.ToArray();//文件流Byte,需要文件流可直接return,不需要下面的保存代码 stmMemory.Close(); MemoryStream m = new MemoryStream(fileBytes); string file = string.Format("F:\\666666666666.pdf");//可根据文件类型自定义后缀 FileStream fs = new FileStream(file, FileMode.OpenOrCreate); m.WriteTo(fs); m.Close(); fs.Close(); } } catch (System.Exception ex) { throw ex; } }
原文地址:https://www.cnblogs.com/xiaoheihei/p/10076973.html
时间: 2024-10-12 07:41:28