根据URL下载文件到本地(将二进制文件保存到磁盘)

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resultUrl);
                            response = request.GetResponse();
                            stream = response.GetResponseStream();

                            if (!response.ContentType.ToLower().StartsWith("text/"))
                            {
                                Value = SaveBinaryFile(response, fileName);
                            }


///


        /// 将二进制文件保存到磁盘
        ///

        ///
        ///
        ///
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                string filePath = FileName.Substring(0, FileName.LastIndexOf("\\"));
                if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
                if (File.Exists(FileName)) File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                int l;

                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0) outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

你可能感兴趣的:(ASP.NET,C#)