1. 程式人生 > >c# 通過地址下載流然後保存文件到本地

c# 通過地址下載流然後保存文件到本地

ont 根據 oid length user toarray mod quest http

        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; } }

c# 通過地址下載流然後保存文件到本地