c# - DownloadFile The process cannot access the file because it is being used by another process -


i have downloader downloading files , runs fine part, ever start throwing exceptions. exception is:

[11:15:34 a.m.] >> [error startdownloadfile] exception occurred during webclient request. | system.io.ioexception: process cannot access file 'a:\users\user\downloads\test\file.extention' because being used process.    @ system.io.__error.winioerror(int32 errorcode, string maybefullpath)    @ system.io.filestream.init(string path, filemode mode, fileaccess access, int32 rights, boolean userights, fileshare share, int32 buffersize, fileoptions options, security_attributes secattrs, string msgpath, boolean bfromproxy, boolean uselongpath, boolean checkhost)    @ system.io.filestream..ctor(string path, filemode mode, fileaccess access, fileshare share, int32 buffersize, fileoptions options, string msgpath, boolean bfromproxy)    @ system.io.filestream..ctor(string path, filemode mode, fileaccess access)    @ system.net.webclient.downloadfile(uri address, string filename) 

the code using is:

while (true)             {     try         {             downloadurl = new uri(result.url);             var filename = dir + "\\" + escapefilename(result.passedfilename) + ".extention";              while (true)             {                 using (var client = new webclient())                 {                     client.downloadfile(downloadurl, filename);                 }                  long filesize = new fileinfo(filename).length;                 if (filesize < 1000)                 {                     log("[error] " + result.passedfilename + " failed, re-downloading");                 }                 else                 {                     break;                 }             }             break;         }         catch (exception ex)         {             log("[error startdownloadfile] " + ex.message + " | " + ex.innerexception);         }     } 

now looking @ other asking similar questions fix use garbage collection or along lines, since i'm using webclient downloadfile assume build in. i'm not sure throwing exception , how fix it

there possibility downloadfile() function returns before os//framework unlocks file. this may explain why garbage collection seems solve problem : delays access file.

in case, work around :

for (int i=0; i<20; i++) // time out = 20*100 ms = 2 seconds try  {    // code accessing file   i=999 ; // exit loop  }  catch { system.thread.threading.sleep(100) ; } 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -