winforms - Web api large file download with HttpClient -
i have problem large file download web api win forms app. on win form app i'm using httpclient grabbing data. have following code on server side:
[httppost] [route] public async task<httpresponsemessage> getbackup(backuprequestmodel request) { httpresponsemessage response; try { response = await task.run<httpresponsemessage>(() => { var directory = new directoryinfo(request.path); var files = directory.getfiles(); var lastcreatedfile = files.orderbydescending(f => f.creationtime).firstordefault(); var filestream = lastcreatedfile.openread(); var fileresponse = new httpresponsemessage(httpstatuscode.ok); fileresponse.content = new streamcontent(filestream); fileresponse.content.headers.contenttype = new mediatypeheadervalue("application/octet-stream"); return fileresponse; }); } catch (exception e) { logger.error(e); response = request.createresponse(httpstatuscode.internalservererror); } return response; }
on client side:
private async void btnstart_click(object sender, eventargs e) { var requestmodel = new backuprequestmodel(); requestmodel.username = txtusername.text; requestmodel.password = txtpassword.text; requestmodel.path = txtserverpath.text; var client = new httpclient(); var result = await client.postasjsonasync("http://localhost:50116/api/backup", requestmodel); var stream = await result.content.readasstreamasync(); var localpath = @"d:\test\filenew.bak"; var filestream = file.create(localpath); stream.copyto(filestream); filestream.close(); stream.close(); filestream.dispose(); stream.dispose(); client.dispose(); } }
this working, purpose of program grab large files on 3gb , save client.
i have tried on files sized 630mb notice is: when call web api http client, http client loads 630mb in memory stream, , memory stream file stream, when try load different file i'm getting outofmemoryexception. happening because application doesn't release memory previous loaded file. can see in task manager holding 635mb of ram memory.
my question how can write data directly httpclient file without using memory stream, or in other words how can write data file while httpclient downloading data?
to make request, use sendasync overload allows specify httpcompletionoption , use responseheadersread
. you'll have manually build request though, without using postasjsonasync
convenience method.
Comments
Post a Comment