我目前正在制作一个允许用户输入最多6个目录的软件,每个目录都保存为字符串(在数组中),然后循环用于检查数组和任何不是null,即实际分配的目录是要压缩到自己的存档中。这是我到目前为止的代码。
private void ZipIt()
{
int nxtFileNum = 0;
string Destination = @"C:\tmpZip" + nxtFileNum + ".zip";
// Check all fields, check if empty, if not save to Selection array
// Seems a inefficient - Possibly loop through Text box control type and collect?
if (String.IsNullOrEmpty(tboxSelect1.Text) == false) { BckupArray[0] = tboxSelect1.Text; };
if (String.IsNullOrEmpty(tboxSelect2.Text) == false) { BckupArray[1] = tboxSelect2.Text; };
if (String.IsNullOrEmpty(tboxSelect3.Text) == false) { BckupArray[2] = tboxSelect3.Text; };
if (String.IsNullOrEmpty(tboxSelect4.Text) == false) { BckupArray[3] = tboxSelect4.Text; };
if (String.IsNullOrEmpty(tboxSelect5.Text) == false) { BckupArray[4] = tboxSelect5.Text; };
if (String.IsNullOrEmpty(tboxSelect6.Text) == false) { BckupArray[5] = tboxSelect6.Text; };
// Create a new ZipFile entity and then loop through each array member, checking if
// it has an assigned value, if so compress it, if not, skip it.
using (ZipFile ZipIt = new ZipFile())
{
nxtFileNum++;
foreach (String q in BckupArray)
{
if (q != null)
{
ZipIt.AddDirectory(q);
ZipIt.Comment = "This archive was created at " + System.DateTime.Now.ToString("G");
ZipIt.Save(Destination);
}
}
}
}
我想要做的是将给定位置的第一个用户保存到tmpZip0.7z,将第二个用户保存到tmpZip1.7z等等,但是目前所做的只是将每个目录添加到tmpZip0.zip。
另外作为附注,如何在选择存档的目录之后命名每个档案?
我目前正在使用DotNetZip(Ionic.Zip)dll。
我希望我能提供足够的信息。
答案 0 :(得分:0)
嗯, 可以执行此操作:
var strings = Controls.OfType<TextBox>()
.Select(x => x.Text)
.Where(text => !string.IsNullOrEmpty(text))
.ToList();
using (ZipFile ZipIt = new ZipFile())
{
nxtFileNum++;
string comment = string.Format("This archive was created at {0:G}",
DateTime.Now);
foreach (string directory in strings)
{
ZipIt.AddDirectory(directory);
ZipIt.Comment = comment;
ZipIt.Save(Destination + "." + nxtFileNum);
}
}
这显然会拉所有文本框。另一种方法是使用类型List<TextBox>
或类似的集合而不是六个不同的变量。
请注意,即使用户未指定前三个名称,总是创建.1,.2,.3等。如果您想完全忠实于用户的定位,请告诉我。
顺便说一下,我不清楚你应该真的重复使用相同的ZipFile
对象。我希望这更合适:
string comment = string.Format("This archive was created at {0:G}",
DateTime.Now);
int fileIndex = 0;
foreach (string directory in strings)
{
fileIndex++;
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddDirectory(directory);
zipFile.Comment = comment;
zipFile.Save(Destination + "." + fileIndex);
}
}
(注意我如何将变量重命名为更常规,顺便说一下 - 变量通常以小写字母开头。)
答案 1 :(得分:0)
你需要切换一些东西:
foreach (String q in BckupArray)
{
nxtFileNum++;
if (q != null)
{
using (ZipFile ZipIt = new ZipFile())
{
string Destination = @"C:\tmpZip" + nxtFileNum + ".zip";
ZipIt.AddDirectory(q);
ZipIt.Comment = "This archive was created at " +
System.DateTime.Now.ToString("G");
ZipIt.Save(Destination);
}
}
}
原因:
Destination
后,它就会被修复。它不会改变,只是因为你增加了nxtFileNum
。ZipFile
而且您只增加了一次nxtFileNum
,因为这些不在您的foreach
循环中if
可确保仅在实际使用时才创建实例。