簡體   English   中英

如何獲取字節數組中包含的文件數?

[英]How to Get the number of files included in a byte array?

我正在使用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;

字節數組就是它的本質-字節序列。 僅通過查看字節數組就無法知道“文件數”。 您需要解壓縮字節數組。

但是,當您在壓縮時遍歷一組文件時,很容易在每個處理的文件中增加一個變量並返回該變量。

為了說明注釋,使用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;

您可以使用2個屬性返回對象:壓縮字節數組和文件數。 另外,請使用string.Format(或Path.Combine)代替string.Concat

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 

拉鏈前

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM