Csharp:WebClient and WebRequest use http download file

简介: //Csharp:WebClient and WebRequest use http download file //20140318 塗聚文收錄 string filePath = "20140302.pdf"; string fileName = "http://www.dusystem.com/3.pdf"
//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();
                }
            }

目录
相关文章
|
4月前
File和FTP和HTTP软件配置
File和FTP和HTTP软件配置
|
2月前
|
JavaScript 网络架构
vue-router.mjs:3252 TypeError: Cannot use ‘in‘ operator to search for ‘validateStatus‘ in http://loc
vue-router.mjs:3252 TypeError: Cannot use ‘in‘ operator to search for ‘validateStatus‘ in http://loc
Springboot Http文件的访问 Url 转换 MultipartFile ,File 转 MultipartFile
Springboot Http文件的访问 Url 转换 MultipartFile ,File 转 MultipartFile
871 0
|
API 开发工具 git
解决 `remote: You must use a personal access token with 'api' scope for Git over HTTP.`
`git clone` 报错,解决 `remote: You must use a personal access token with 'api' scope for Git over HTTP.`
425 0
解决 `remote: You must use a personal access token with 'api' scope for Git over HTTP.`
|
Java
SpringBoot报错:端口被占用Address already in use(Failed to start component [Connector[HTTP/1.1-8080)
SpringBoot报错:端口被占用Address already in use(Failed to start component [Connector[HTTP/1.1-8080)
378 0
SpringBoot报错:端口被占用Address already in use(Failed to start component [Connector[HTTP/1.1-8080)
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p
|
对象存储
上传文件到OSS报错:[Server]Unable to execute HTTP request: Position is not equal to file length
上传文件到OSS报错:[Server]Unable to execute HTTP request: Position is not equal to file length
1117 0
|
Web App开发
How to use Chrome HAR save HTTP performance
How to use Chrome HAR save HTTP performance
128 0
How to use Chrome HAR save HTTP performance
file encode - /UI2/CL_HTTP_FILE_ENCODE
Created by Wang, Jerry, last modified on Mar 24, 2015
114 0
file encode - /UI2/CL_HTTP_FILE_ENCODE
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p
成功解决 SyntaxError: Non-UTF-8 code starting with \xc0 in file but no encoding declared; see http://p