簡體   English   中英

如何在制作 zip 文件之前將文件內容制作為 base64 編碼

[英]how to make file content as base64 encoded before making zip file

我有一個目錄,其中有CSV文件,我需要首先將文件內容編碼為base64字符串,然后將其作為zip文件。

我可以使用以下代碼將文件制作為 zip ,但在兩者之間如何將文件內容制作為 base64 編碼? 謝謝!

 var csvFiles = Directory.GetFiles(@"C:\Temp", "*.csv")
            .Select(f => new FileInfo(f));

        foreach (var file in csvFiles)
        {
            using (var newFile = ZipFile.Open($@"C:\tmp\{Path.GetFileNameWithoutExtension(file.Name)}.zip",
                ZipArchiveMode.Create))
            {
                newFile.CreateEntryFromFile($@"C:\Temp\{file.Name}",
                    file.Name);
            }
        }

無視你的動機或其他問題(概念或其他)

這是一個分配最少的完全流式解決方案(讓我們對您的大型 Object 堆好點)。 帶有ToBase64TransformCryptoStream只是 stream base64 編碼的一種方式

var csvFiles = Directory.GetFiles(@"D:\Temp");
using var outputStream = new FileStream(@"D:\Test.zip", FileMode.Create);
using var archive = new ZipArchive(outputStream, ZipArchiveMode.Create, true);
foreach (var file in csvFiles)
{
   using var inputFile = new FileStream(file, FileMode.Open, FileAccess.Read);
   using var base64Stream = new CryptoStream(inputFile, new ToBase64Transform(), CryptoStreamMode.Read);
   var entry = archive.CreateEntry(Path.GetFileName(file));
   using var zipStream = entry.Open();
   base64Stream.CopyTo(zipStream);
}

您需要創建 base64 字符串,將其轉換為字節數組,然后從字節數組創建存檔條目(通過創建流)。

像這樣的東西應該可以完成這項工作:

var dirInfo = new DirectoryInfo(@"C:\Temp");
var csvFiles = dirInfo.GetFiles("*.csv");   // This already returns a `FileInfo[]`.

foreach (var file in csvFiles)
{
    var fileBytes = File.ReadAllBytes(file.FullName);
    var base64String = Convert.ToBase64String(fileBytes);
    var base64Bytes = Encoding.UTF8.GetBytes(base64String);

    string newFilePath = $@"C:\tmp\{Path.GetFileNameWithoutExtension(file.Name)}.zip";
    using (var newFile = ZipFile.Open(newFilePath, ZipArchiveMode.Create))
    {
        // You might want to change the extension 
        // since the file is no longer in CSV format.
        var zipEntry = newFile.CreateEntry(file.Name);

        using (var base64Stream = new MemoryStream(base64Bytes))
        using (var zipEntryStream = zipEntry.Open())
        {
            base64Stream.CopyTo(zipEntryStream);
        }
    }
}

或者,您可以將 base64 字符串保存到臨時文件,從文件創建條目,然后將其刪除; 但是當工作可以在 memory 中完成時,我不喜歡將虛擬數據寫入磁盤。

暫無
暫無

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

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