且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Csharp:WebClient and WebRequest use http download file

更新时间:2022-08-14 15:37:02

//Csharp:WebClient and WebRequest use http download file
            //20140318 塗聚文收錄
            string filePath = "20140302.pdf";
            string fileName = "http://www.dusystem.com/3.pdf";


            //1出现找不到文件 filePath
            //string headerValue = (Request.UserAgent.ToLower().Contains("msie"))? string.Format("attachment; filename=\"{0}\"", Uri.EscapeDataString(fileName)): string.Format("attachment; filename=\"{0}\"", fileName); //for Firefox, Chrome, Safari, Opera
            //Response.Clear();
            //Response.ContentType = "text/plain";
            //Response.AddHeader("Content-Disposition", headerValue);
            //Response.TransmitFile(filePath);
            //Response.End();


            //2: 有效   WebException ex
            //System.Net.WebClient net = new System.Net.WebClient();
            //string link = fileName;
            //Response.ClearHeaders();
            //Response.Clear();
            //Response.Expires = 0;
            //Response.Buffer = true;
            //Response.AddHeader("Accept-Language", "utf-8");
            //Response.AddHeader("Content-Disposition", "Attachment;FileName=" + System.Web.HttpUtility.UrlEncode(link, System.Text.Encoding.UTF8));
            //Response.ContentType = "APPLICATION/octet-stream";
            //Response.BinaryWrite(net.DownloadData(link));
            //Response.End();


            //3:有效,但文件是空
            //string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            //string myFileName = dir + @"\213.pdf";
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileName);  //
          
            //request.MaximumResponseHeadersLength = 40000;
            //request.Timeout = 20000;
            //request.Credentials = CredentialCache.DefaultCredentials;
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //Stream receiveStream = response.GetResponseStream();
            //StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            //using (StreamWriter sw = new StreamWriter(myFileName, false, Encoding.UTF8))
            //{
            //    sw.Write(readStream.ReadToEnd());
            //    sw.Flush();
            //    sw.Close();

            //}


            //4。有效
            //byte[] result;
            //byte[] buffer = new byte[4096];
            //string link = fileName;
            //WebRequest wr = WebRequest.Create(fileName);
            //WebResponse response = wr.GetResponse();
            //Stream responseStream = response.GetResponseStream();
            //MemoryStream memoryStream = new MemoryStream();
            //Response.AddHeader("Accept-Language", "utf-8");
            //Response.AddHeader("Content-Disposition", "Attachment;FileName=" + System.Web.HttpUtility.UrlEncode(link, System.Text.Encoding.UTF8));
            //Response.ContentType = "APPLICATION/octet-stream";
            //int count = 0;
            //do
            //{
            //    count = responseStream.Read(buffer, 0, buffer.Length);
            //    memoryStream.Write(buffer, 0, count);
            //    Response.BinaryWrite(buffer);
            //    //Response.OutputStream.Write(buffer,0,count);
            //}
            //while (count != 0);
            //result = memoryStream.ToArray();


            //5。有效
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullFileName = dir + @"\213.pdf";
            HttpWebRequest hRequest = (HttpWebRequest)WebRequest.Create(fileName);
            WebResponse response = hRequest.GetResponse();
            using (response = (HttpWebResponse)hRequest.GetResponse())
            {
                /*Download the file to the fullFileName location */
                Stream streamResponse = response.GetResponseStream();
                if (streamResponse != null)
                {
                    byte[] inBuf = new byte[response.ContentLength];
                    int bytesToRead = System.Convert.ToInt32(inBuf.Length);
                    int bytesRead = 0;
                    while (bytesToRead > 0)
                    {
                        int n = streamResponse.Read(inBuf, bytesRead, bytesToRead);
                        if (n == 0)
                        {
                            break;
                        }
                        bytesRead += n;
                        bytesToRead -= n;
                    }

                    FileStream fstr = new FileStream(fullFileName, FileMode.OpenOrCreate, FileAccess.Write);
                    fstr.Write(inBuf, 0, bytesRead);
                    streamResponse.Close();
                    streamResponse.Dispose();
                    fstr.Close();
                    fstr.Dispose();
                }
            }