JSW*_*ter 4 .net c# io zip winforms
我意识到这个问题有几个变体,但在审查它们时,我没有看到我的确切用例,而且我的结果有问题。
我正在做的是将一些 BZ2 压缩文件通过 FTP 传输到我硬盘上的一个文件夹中。然后我将每个文件解压缩以供审阅。最后,我想通过电子邮件将文件发送给某人,但我想先将它们放入 Zip 存档中以使其更容易。下面是代码。
private void buttonCreateZip_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(@"C:\temp\logfiles\" + comboBoxDirectory.SelectedItem.ToString() + "\\zip\\");
string startPath = @"C:\temp\logfiles\" + comboBoxDirectory.SelectedItem.ToString();
string zipPath = @"C:\temp\logfiles\" + comboBoxDirectory.SelectedItem.ToString() + "\\zip\\" + comboBoxDirectory.SelectedItem.ToString() + ".zip";
File.SetAttributes(@"C:\temp\logfiles\" + comboBoxDirectory.SelectedItem.ToString() + "\\zip\\", FileAttributes.Normal);
File.SetAttributes(@"C:\temp\logfiles\" + comboBoxDirectory.SelectedItem.ToString() + "\\", FileAttributes.Normal);
ZipFile.CreateFromDirectory(startPath, zipPath);
}
Run Code Online (Sandbox Code Playgroud)
我不会单独组合这些文件,而是使用 API 获取目标目录中的所有文件并将它们压缩到存档中。
问题是即使我得到了例外
进程无法访问文件“C:...”,因为它正在被另一个进程使用”
无论如何,它都会在我为此目的创建的 zip 子目录中创建 ZIP 存档。它几乎看起来像是在库函数内部CreateFromDirectory,但这是我通过引用访问的标准库的一部分:
系统.IO.压缩.文件系统。
压缩文件的目标目录:
@"C:\temp\logfiles\[Some Name]\Zip"
包含在源目录的路径中,压缩操作的基本目录:
@"C:\temp\logfiles\[Some Name]。
ZipFile.CreateFromDirectory包括基本目录的子目录树结构及其在创建压缩文件时的内容,因此它还尝试压缩它正在创建的目标文件。当然它无法访问它,因为它(猜猜是什么)正在使用中。
如果将目标目录移至基本路径之外,则不会引发任何异常。
您可以使用用户Temp目录作为压缩文件的临时目标,然后在完成后将其移动到目标目录。
用户临时目录由Environment.GetEnvironmentVariable()返回:
Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.User);
Run Code Online (Sandbox Code Playgroud)
您还需要删除临时 zip 文件,并在任何情况下验证它是否已存在(具有该名称的文件可能因任何原因而存在,尝试覆盖它会导致错误)。
使用用户临时目录创建 ZipFile 的可能方法示例:
string SourceFolder = @"C:\temp\logfiles\";
string DestinationFolder = @"C:\temp\logfiles\Zip";
string ZippedFileName = "ZippedFile.zip";
string UserTempFolder = Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.User);
string ZippedTempFile = Path.Combine(UserTempFolder, ZippedFileName);
if (File.Exists(ZippedTempFile)) { File.Delete(ZippedTempFile); }
ZipFile.CreateFromDirectory(SourceFolder, ZippedTempFile);
Directory.CreateDirectory(DestinationFolder);
File.Move(ZippedTempFile, Path.Combine(DestinationFolder, ZippedFileName));
Run Code Online (Sandbox Code Playgroud)