c# - How to avoid the 0-byte file on Webclient download error -


when using following code download file:

webclient wc = new webclient(); wc.downloadfilecompleted += new system.componentmodel.asynccompletedeventhandler(wc_downloadfilecompleted); wc.downloadfileasync("http://path/file, "localpath/file"); 

and error occurs during download (no internet connection, file not found, etc.) allocates 0-byte file in localpath/file can quite annoying.

is there way avoid in clean way?

(i probe 0 byte files on download error , delete it, dont think recommended solution)

if reverse engineer code webclient.downloadfile see filestream instantiated before download begins. why file created if download fails. there's no way ammend code should cosnider different approach.

there many ways approach problem. consider using webclient.downloaddata rather webclient.downloadfile , creating or writing file when download complete , sure have data want.

webclient client = new webclient();  client.downloaddatacompleted += (sender, eventargs) => {     byte[] filedata = eventargs.result;     //did receive data successfully? place own condition here.      using (filestream filestream = new filestream("c:\\users\\alex\\desktop\\data.rar", filemode.create))         filestream.write(filedata, 0, filedata.length); };  client.downloaddataasync(address); client.dispose(); 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -