将压缩压缩文件到内存流 - C#
本文关键字:压缩 文件 内存 | 更新日期: 2023-09-27 18:31:05
我已经编写了代码来将zip文件的编码字符串存储到临时路径中,现在我想将编码的zip文件字符串存储到内存流而不是临时路径。有人可以帮我如何读取流并将其作为字符串传递给 ZipFile 类......我正在使用 DOTNETZIP 库来解压缩密码抗议文件。请参阅下面的代码。
string tempPath = Path.GetTempPath();
foreach (ActivityMimeAttachment a in attachments.Entities)
{
if (a.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
string strcontent = a.Body;
byte[] filecontent = Convert.FromBase64String(strcontent); // unpack the base-64 to a blob
File.WriteAllBytes(tempPath + a.FileName, filecontent); // Working code creates a zip file
string attachmentfile = tempPath + a.FileName;
using (ZipFile zip = new ZipFile(attachmentfile))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractWithPassword(tempPath, "password");
FileStream inFile;
byte[] binaryData;
string file = tempPath + entry.FileName;
inFile = new FileStream(file, FileMode.Open, FileAccess.Read);
binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0,
(int)inFile.Length);
inFile.Close();
您需要
将文件内容转换为内存流(Stream filestream = new MemoryStream(filecontent)
),然后使用ZipFile.Read(fileStream)
。然后使用StreamReader
将内容作为字符串取出。所以试试这样的东西(注意它是未经测试的):
string myString;
byte[] filecontent = Convert.FromBase64String(strcontent);
using (var filestream = new MemoryStream(filecontent))
{
using (ZipFile zip = ZipFile.Read(filestream))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
using (var ms = new MemoryStream())
{
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
var sr = new StreamReader(ms);
myString = sr.ReadToEnd();
}
...
如果结果应为 base64 字符串,请执行以下操作:
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
myString = Convert.ToBase64String(ms.ToArray());
您可能必须重置也可能不需要重置流位置,但最好这样做。
现在,您可以将结果用作字符串,而无需先写入文件。