我正在遍历目录并压缩其中的文件。在下面的代码中,我将原始文件添加到zipOutputStream,然后删除该文件。 使用下面的代码,我得到以下异常:
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
我知道发生此异常是因为文件正在压缩并且我同时将其删除?如果是这样,我如何确保在删除之前发生压缩?
这是我的代码:
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());
}
我正在使用以下库:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
答案 0 :(得分:1)
在完成所有压缩后,如何运行第二个循环来进行删除?
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);
}
oStream.Finish();
oStream.Close();
}
// Delete the files now.
for (int j = 0; j < i; j++)
{
string fileToZip = sorted.ElementAt(j);
File.Delete(fileToZip);
}
// limitIndex = i - 1;
startIndex = i - 1;
zipNumber += 1;
size = 0;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}