c# - File.Delete the process cannot access the file because it is being used by another process -
public bool downloadmp3file (downloadedmp3 mp3) { webclient client = new webclient (); string filepath = ""; bool wasdownload = false; try { string song = mp3.songname; filepath = @"mp3\" + song + ".mp3"; if (file.exists (filepath)) { file.delete (filepath); } datetime trycountnow = datetime.now; client = new webclient (); client.downloadfileasync (new uri (mp3.url), filepath); client.downloadprogresschanged += client_downloadprogresschanged; client.downloadfilecompleted += client_downloadfilecompleted; datetime start = datetime.now; bool notdownload = false; downloadcomplete = false; while (!downloadcomplete) { datetime = datetime.now; timespan ts = - start; int min = ts.minutes; int sec = ts.seconds; if (10 < sec && 0 == downloadprogress) { notdownload = true; client.cancelasync (); break; } if (min == 1) { notdownload = true; client.cancelasync (); break; } thread.sleep (30); } if (!notdownload) { client.cancelasync (); client.openread (mp3.url); int downloadedfilesize = convert.toint32 (client.responseheaders["content-length"]); fileinfo localfile = new fileinfo (filepath); if (localfile.length == downloadedfilesize) { wasdownload = true; } } } catch { downloadprogress = 0; downloadcomplete = false; } { client.cancelasync (); client.dispose (); downloadcomplete = false; downloadprogress = 0; gc.collect (); if (!wasdownload) { if (file.exists (filepath)) { filesecurity fs = file.getaccesscontrol (filepath); file.delete (filepath); } } application.current.dispatcher.begininvoke ( dispatcherpriority.background, new action (() => mainwindow.label3.content = "" )); } return wasdownload; }
please help! exception:
file.delete process cannot access file because being used process
i can't find out why (i disposed webclient).
your code suggests you're getting "file being used" exception on file newly downloaded. many anti-virus programs automatically scan newly created and/or newly downloaded files, , may delay closing file handle until scan done.
if problem, there's nothing more can close file on time. can either switch different anti-virus doesn't keep files locked during scans, or can implement delay+retry loop when trying use file that's been closed.
Comments
Post a Comment