I am looping through a directory and zip the files in it. In the following code, I am adding the original file to a zipOutputStream, and then delete the file. With the code below, I get the following exception:
Exception thrown: 'System.IO.IOException' in mscorlib.dll
System.IO.IOException: The process cannot access the file 'C:\Users\Desktop\test.zip' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at 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)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.OpenRead(String path)
at ZipFiles.zipFile(String fileToZip, ZipOutputStream oStream) in C:\Users\Desktop\CodeFile1.cs:line 34
at ZipFiles.zipByFileSize(String dir) in C:\Users\Desktop\CodeFile1.cs:line 75
I understand that this exception occurs because the file is being zipped and I am deleting it at the same time? if so, how do I make sure that the zipping happens before the deleting?
Here is my code:
try
{
using (ZipOutputStream oStream = new ZipOutputStream(File.Create(zipPath)))
{
oStream.SetLevel(8); // 9 = highest compression
for (int j = 0; j < i; j++)
{
string fileToZip = sorted.ElementAt(j);
zipFile(fileToZip, oStream);
File.Delete(fileToZip);
}
oStream.Finish();
oStream.Close();
}
// limitIndex = i - 1;
startIndex = i - 1;
zipNumber += 1;
size = 0;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
I am using the following libraries:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;