I have a ZipArchiveEntry which is an Excel file and want to convert it to a FileStream. How can I do it? Also I don't have information about the path for the file. Basically this is the code I have:
var zipArchive = new ZipArchive(InputStream);
foreach (var entry in zipArchive.Entries)
{
using (var stream = entry.Open())
{
//Conversion stream => FileStream
}
}
CodePudding user response:
Stream.CopyTo - Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.
var zipArchive = new ZipArchive(InputStream);
foreach (var entry in zipArchive.Entries)
{
using (var fileStream = new FileStream(outputFileName, FileMode.Create))
using (var stream = entry.Open())
{
stream.CopyTo(fileStream);
}
}
CodePudding user response:
You can extract entries into temp folder and work with them.
const string tempFolder = ".temp";
var entryFileStreams = new List<FileStream>();
using (var archive = new ZipArchive(InputStream))
{
// extracting excel files into temp folder
foreach (ZipArchiveEntry entry in archive.Entries)
{
string destinationFileName = Path.Combine(tempFolder, entry.Name);
FileStream entryFileStream = File.Create(destinationFileName);
Stream entryStream = entry.Open();
entryStream.CopyTo(entryFileStream);
entryFileStreams.Add(entryFileStream);
}
}
// work with FileStream's
foreach (FileStream entryStream in entryFileStreams)
{
DoSomething(entryStream);
}
// disposing FileStream's
entryFileStreams.ForEach(entryStream => entryStream.Dispose());
// deleting entry temp files
Directory.Delete(tempFolder, true);