lucas.mdo
lucas.mdo

Reputation: 439

Exception when using ZipOutputStream and FileStream to zip files

I'm creating several backup files every couple of seconds in order to ensure the integrity of my system (requirement).

Because it is a lot of files, I'm using ZipOutputStream to zip files and save some space in disk. However, when the code reaches the File.OpenRead(filename), it throws the following exception:

The process cannot access the file 'inputfilefullnamehere' because it is being used by another process.

I thought it would be the exactly ZipOutputStream, so I tried to close it before opening the FileStream, but then I got another exception in StreamUtils.Copy() saying that there is no entry openned.

Is there something that I'm missing?

My code is:

byte[] buffer = new byte[4096];

ZipOutputStream s = new ZipOutputStream(File.Create(filename+ ".his"));

s.SetLevel(9); // 0 - store only to 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);

Upvotes: 1

Views: 2316

Answers (1)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5137

You need to pass path of the source file(filename) to the File.OpenRead method, not the destination path. You get the access denied error since you are trying to read destination file which you have already opened to 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 only to 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);

Upvotes: 1

Related Questions