C# Webclient Stream download file from FTP to local storage -
i've been downloading files ftp server via webclient object .net namespace provides , write bytes actual file via binarywriter. good. however, now, files have dramatically increased in size , i'm worried memory constraints i'd create download stream, create file stream, , line line read download , write file.
i'm nervous since couldn't find nice example of this. here's end result:
var request = new webclient(); // omitted code add credentials, etc.. var downloadstream = new streamreader(request.openread(ftpfilepathuri.tostring())); using (var writestream = file.open(tolocation, filemode.createnew)) { using (var writer = new streamwriter(writestream)) { while (!downloadstream.endofstream) { writer.write(downloadstream.readline()); } } } am going incorrect/better way/etc?
have tried following usage of webclient class?
using (webclient webclient = new webclient()) { webclient.downloadfile("url", "filepath"); } update
using (var client = new webclient()) using (var stream = client.openread("...")) using (var file = file.create("...")) { stream.copyto(file); } if want download file explicitly using customized buffer size:
public static void downloadfile(uri address, string filepath) { using (var client = new webclient()) using (var stream = client.openread(address)) using (var file = file.create(filepath)) { var buffer = new byte[4096]; int bytesreceived; while ((bytesreceived = stream.read(buffer, 0, buffer.length)) != 0) { file.write(buffer, 0, bytesreceived); } } }
Comments
Post a Comment