5

How would I basically use ZipFile.CreateFromDirectory to send back zipfile to memory stream instead of a output path.

Or would I have to use ZipArchive and generate the zip file myself? Seems kind of odd there isn't a method for stream.

Here's basically what I'm trying to do

using (MemoryStream ms = new MemoryStream())
{
   ZipFile.CreateFromDirectory(path, ms)
   buf = ms.ToArray();
   LogZipFile(path, filesize, buf.LongLength);
}
jefflahh
  • 49
  • 3
  • You could do something like https://stackoverflow.com/questions/17232414/creating-a-zip-archive-in-memory-using-system-io-compression but do the iteration yourself. – Richardissimo May 07 '18 at 20:17

1 Answers1

1

I implement it base on this https://stackoverflow.com/a/17939367/12634387

public static class FileExtensions
   {
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
     }
   }
 public static byte[] ZipFolders(string folderPath)
    {
        if (Directory.Exists(folderPath))
        {
            DirectoryInfo from = new DirectoryInfo(folderPath);
            using (var zipToOpen = new MemoryStream())
            {
                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    foreach (var file in from.AllFilesAndFolders().OfType<FileInfo>())
                    {
                        var relPath = file.FullName.Substring(from.FullName.Length + 1);
                        ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
                    }
                }
                return zipToOpen.ToArray();
            }
        }
        else
        {
            return null;
        }
    }