您的位置:首页 > 其它

下载文件或图片

2015-12-29 16:44 267 查看
public static void DownloadToLocal(string url, string savePath)

        {

            try

            {

                //string UploadPhysPath = ConfigurationManager.AppSettings["UploadPhysPath"];

                string UploadPhysPath = BLL.CommonFileManager.UploadPhysPath;

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                Stream stream = httpWebResponse.GetResponseStream();

                // 获得请求的文件大小。

                int fileSize = (int)httpWebResponse.ContentLength;

                int bufferSize = 1024;

                byte[] buffer = new byte[bufferSize];

                string directory = Path.GetDirectoryName(UploadPhysPath + savePath);

                if (!Directory.Exists(directory))

                {

                    Directory.CreateDirectory(directory);

                }

                // 建立一个写入文件的流对象。

                FileStream saveFile = File.Create(UploadPhysPath + savePath, bufferSize);

                int bytesRead;

                do

                {

                    bytesRead = stream.Read(buffer, 0, buffer.Length);

                    saveFile.Write(buffer, 0, bytesRead);

                }

                while (bytesRead > 0);

                saveFile.Flush();

                saveFile.Close();

                stream.Flush();

                stream.Close();

            }

            catch (Exception e)

            {

                throw;

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  下载文件或图片