带有用户名密码验证的远程文件下载
try { string getFileName = Url.Substring(Url.LastIndexOf("/") + 1); HttpWebRequest WRequest; // HttpWebResponse response = null; Uri uri = new Uri(Url); CredentialCache cc = new CredentialCache(); WRequest = (HttpWebRequest)HttpWebRequest.Create(uri); WRequest.Credentials = new System.Net.NetworkCredential(DocLibConst.Con_SPUserName, DocLibConst.Con_PWD, DocLibConst.Con_Domain); WRequest.PreAuthenticate = true; WRequest.Method = "GET"; WRequest.AllowWriteStreamBuffering = false; WRequest.SendChunked = false; WRequest.KeepAlive = true; WRequest.ContentLength = 0; //WRequest.SendChunked = true; //WRequest.ContentLength = 100000; WRequest.Timeout = 30000; WRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes("epapi:epapiadmin"))); WebResponse wr = WRequest.GetResponse(); Stream responseStream = wr.GetResponseStream(); MemoryStream mem = new MemoryStream(); //创建本地文件写入流 //Stream stream = new FileStream("D:\\xx.docx", FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { //stream.Write(bArr, 0, size); mem.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } //stream.Write(mem.ToArray(), 0, mem.ToArray().Length); //stream.Close(); responseStream.Close(); Page.Response.ClearContent(); Page.Response.ClearHeaders(); Page.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(getFileName, System.Text.Encoding.UTF8)); Page.Response.AddHeader("Content-Length", mem.ToArray().Length.ToString()); Page.Response.AddHeader("Content-Transfer-Encoding", "binary"); Page.Response.ContentType = "application/octet-stream"; Page.Response.BinaryWrite(mem.ToArray()); Page.Response.Flush(); //page.Response.End(); } catch (Exception ex) { throw ex; } finally { HttpContext.Current.Response.Close(); }