1

我正在使用ICSharpCode.SharpZipLib.Core库来压缩我的 C# 代码中的文件。压缩后我将返回一个字节数组。有什么方法可以找到字节数组中的文件数?

我的代码看起来像

string FilePath ="C:\HELLO";
 MemoryStream outputMemStream = new MemoryStream();
            ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
            foreach (var file in files)
            {
                FileInfo fi = new FileInfo(string.Concat(FilePath, file));
                if (fi.Exists)
                {
                    var entryName = ZipEntry.CleanName(fi.Name);
                    ZipEntry newEntry = new ZipEntry(entryName);
                    newEntry.DateTime = DateTime.Now;
                    newEntry.Size = fi.Length;
                    zipStream.PutNextEntry(newEntry);

                    byte[] buffer = new byte[4096];
                    var fs = File.OpenRead(string.Concat(FilePath, file));
                    var count = fs.Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
                        zipStream.Write(buffer, 0, count);
                        count = fs.Read(buffer, 0, buffer.Length);  
                    }
                }
            }
            zipStream.Close();
            byte[] byteArrayOut = outputMemStream.ToArray();
            return byteArrayOut;
4

3 回答 3

2

字节数组就是它的本来面目——一个字节序列。无法仅通过查看字节数组来了解“文件数”。您需要解压缩字节数组。

但是,当您在压缩时遍历一组文件时,很容易为每个处理的文件增加一个变量并返回它。

为了解释评论,使用out参数而不是Tuple

numFiles = 0;    // This is an out parameter to the method
foreach (var file in files)
{
    FileInfo fi = new FileInfo(string.Concat(FilePath, file));
    if (fi.Exists)
    {
        numFiles++;
        ...
    }
}

...
return byteArrayOut;
于 2013-03-27T08:00:07.490 回答
0

您可以返回具有 2 个属性的对象:压缩字节数组和文件数。此外,使用 string.Format(或 Path.Combine)而不是 string.Concat

于 2013-03-27T08:00:25.083 回答
0

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.80).aspx

利用

var filesCount = 0;

方法外

filesCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length 

拉链前

于 2013-03-27T08:06:55.290 回答