c# 通过地址下载流然后保存文件到本地
1.下载文件并保存文件到本地
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; } }
2.下载文件流,返回byte流
private byte[] GetFileFromNetUrl(string url, string userName = "", string password = "") { try { System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "GET"; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { //获得用户名密码的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 stmMemory.Close(); } return fileBytes; } catch (System.Exception ex) { throw ex; } }