NSoft.NFramework.Networks.HttpClient.DownloadFile C# (CSharp) Метод

DownloadFile() публичный Метод

지정한 주소의 내용을 받아서 파일로 저장한다.
public DownloadFile ( string address, string filename ) : bool
address string 서버 주소
filename string 로칼 파일 경로
Результат bool
        public bool DownloadFile(string address, string filename) {
            if(IsDebugEnabled)
                log.Debug("Download a file from the specified address. address=[{0}], filename=[{1}]", address, filename);

            bool downloaded = false;
            try {
                _responseHeaders = null;
                WebRequest request = WebRequest.Create(GetUri(address));
                request.Credentials = Credentials;
                request.Proxy = WebProxy;

                WebResponse response = request.GetResponse();

                _responseHeaders = response.Headers;

                // 적당한 버퍼 크기를 결정한다.
                var length = response.ContentLength;

                if(length == -1 || length > int.MaxValue) {
                    length = int.MaxValue;
                }

                var buffer = new byte[(uint)Math.Min(HttpConsts.DEFAULT_BUFFER_LENGTH, (int)length)];

                using(var stream = response.GetResponseStream())
                using(var bs = FileTool.GetBufferedFileStream(filename, FileOpenMode.Write)) {
                    int readCount;
                    do {
                        readCount = stream.Read(buffer, 0, buffer.Length);
                        if(readCount > 0)
                            bs.Write(buffer, 0, readCount);
                    } while(readCount > 0);

                    bs.Flush();
                }

                if(IsDebugEnabled)
                    log.Debug("Download File is SUCCESS!!! filename=[{0}]", filename);

                downloaded = true;
                return true;
            }
            catch(Exception ex) {
                if(log.IsErrorEnabled) {
                    log.Error("Fail to download a filename=[{0}]", filename);
                    log.Error(ex);
                }

                throw;
            }
            finally {
                // 다운로드에 실패하고, 파일이 존재한다면, 완전한 파일이 아니므로 삭제해버린다.
                //
                if(downloaded == false && filename.FileExists())
                    filename.DeleteFile(false);
            }
        }

Usage Example

Пример #1
0
        public void DownloadFile() {
            var http = new HttpClient();

            http.DownloadFile(FileUrl, @"C:\Temp\File.doc");
        }
All Usage Examples Of NSoft.NFramework.Networks.HttpClient::DownloadFile