我正在循环访问一个目录并压缩其中的文件。在下面的代码中,我将原始文件添加到 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;
最佳答案
完成所有压缩后运行第二个循环来执行删除怎么样?
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());
}
关于c# - 压缩后删除原文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49538403/