【问题标题】:How would I implement zipping all the files in a folder into my code?我将如何实现将文件夹中的所有文件压缩到我的代码中?
【发布时间】:2018-02-01 17:23:39
【问题描述】:

到目前为止,我有一个代码每 2 秒截取一次屏幕截图并将它们保存到 a 文件夹中。我想为程序添加一个功能,每 2 小时截取一次屏幕截图并将它们压缩。我目前正在尝试弄清楚如何在我的代码中设置单独的计时器,但之后我需要添加它。

我一直在寻找并尝试学习如何做到这一点,但是我对 c# 代码的了解非常有限。

我尝试将以下内容添加到我的代码中

using System.IO.Compression

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = @"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);

但它返回“不需要使用指令”。用于 System.IO.Compression。另外,我无法弄清楚我的 C:\Intel\Logs\dsp 目录如何适合每个字段,即。

c:\example\start
c:\example\result.zip
c:\example\extract

谁能帮我弄清楚我做错了什么并向我解释(用非常明目张胆的语言)我该如何解决它? 非常感谢!

附:在这部分中添加会创建 zip 文件并使其隐藏吗?另外,那我应该为那条线放哪条路径?

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
File.SetAttributes("c:\example\whichpath", FileAttributes.Hidden); //HERE
string extractPath = @"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);

【问题讨论】:

  • 在 MSDN 的 System.IO.Compression.ZipFile.CreateFromDirectory() documentation 中有一个示例(在 C# 和 VB.Net 中)。它不能准确地显示你需要什么吗?你为什么要压缩它们然后立即解压缩它们?您可以删除 100% 的代码并最终得到相同的结果,而不会在您不使用的文件夹中出现 .zip 文件的混乱。
  • 老实说,我刚刚离开this。我不知道我在做什么。实际上,我尝试阅读您发送给我的链接几次,但我只是不明白,所以我想我可能会在论坛上发帖寻求帮助。
  • 没什么好理解的。代码示例是一个非常简单、非常清晰的函数使用示例。 (您正在查看标题示例下的示例代码,对吗?)如果您看不懂,您将如何阅读此处的答案?跨度>
  • 哦,好的。对不起,我的线路组织有一个小错误。我现在已经修好了。我唯一不明白的是我的 C:\Intel\Logs\dsp 目录如何适合每个字段(即c:\example\startc:\example\result.zipc:\example\extract)。
  • 另外,如果我不尝试在压缩后立即提取 zip 文件,为什么该示例包含 string extractPath = @"c:\example\extract";ZipFile.ExtractToDirectory(zipPath, extractPath);

标签: c# visual-studio-2017


【解决方案1】:

来自here,您需要添加以下评论推荐的内容:

using System.IO.Compression;
using System.IO.Compression.FileSystem;

...

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";

ZipFile.CreateFromDirectory(startPath, zipPath);

// and hide it
File.SetAttributes(zipPath, File.GetAttributes(zipPath) | FileAttributes.Hidden);

【讨论】:

  • 这不是我目前拥有的吗? (除了文件属性部分)或者我错过了什么? (我刚刚意识到这可能听起来很粗鲁,但我向你保证我实际上只是很困惑。感谢您的帮助。)
  • @Rosa1995:您在using 行的末尾缺少;,并且缺少另一个using
  • 哦!我现在看到了。太感谢了!我不敢相信我错过了这么小的问题。
  • 我也很困惑,如果我不尝试在压缩文件后立即提取 zip 文件,为什么还要包含 string extractPath = @"c:\example\extract";ZipFile.ExtractToDirectory(zipPath, extractPath);。我可以排除它并写成this吗?
  • 没关系。肯怀特帮我弄清楚了。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 2012-05-25
  • 2016-01-05
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多