c# - Exception when using ZipOutputStream and FileStream to zip files -


i'm creating several backup files every couple of seconds in order ensure integrity of system (requirement).

because lot of files, i'm using zipoutputstream zip files , save space in disk. however, when code reaches file.openread(filename), throws following exception:

the process cannot access file 'inputfilefullnamehere' because being used process.

i thought zipoutputstream, tried close before opening filestream, got exception in streamutils.copy() saying there no entry openned.

is there i'm missing?

my code is:

byte[] buffer = new byte[4096];  zipoutputstream s = new zipoutputstream(file.create(filename+ ".his"));  s.setlevel(9); // 0 - store 9 - means best compression  zipentry entry = new zipentry(filename+ ".his");  s.putnextentry(entry);  using (filestream fs = file.openread(filename+ ".his")) {     streamutils.copy(fs, s, buffer); }  s.close();  file.delete(filename); 

you need pass path of source file(filename) file.openread method, not destination path. access denied error since trying read destination file have opened write to.

string sourcefilename = filename; string destfilename = string.format("{0}.his", filename);  using (zipoutputstream s = new zipoutputstream(file.create(destfilename)) {     s.setlevel(9); // 0 - store 9 - means best compression         zipentry entry = new zipentry(filename);         s.putnextentry(entry);         using (filestream fs = file.openread(sourcefilename)) {         byte[] buffer = new byte[4096];         streamutils.copy(fs, s, buffer);     }         s.close();     } file.delete(filename); 

Comments