【问题标题】:zip a file programatically like native send to compressed zip folder以编程方式压缩文件,如本机发送到压缩的 zip 文件夹
【发布时间】:2021-10-01 09:13:45
【问题描述】:

我必须将压缩文件发送到外部应用程序。另一端的支持表示应用程序无法读取我以编程方式创建的文件。这就是我创建文件的方式:

using System.IO;
using System.IO.Compression;

const string ZIPPATH = @".\stock.zip";
const string PACKAGEPATH = @".\stock\content";
const string APPPACKAGE = @".\stock";
const string PACKAGEFILENAME = @"content\Offers.xml";

private void CreateZipArchive()
{
    if (!Directory.Exists(PACKAGEPATH)) Directory.CreateDirectory(PACKAGEPATH);

    if (File.Exists(ZIPPATH)) File.Delete(ZIPPATH);

    ZipFile.CreateFromDirectory(APPPACKAGE, ZIPPATH);
    using (FileStream fs = new FileStream(ZIPPATH, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Update))
    {
        ZipArchiveEntry zae = archive.CreateEntry(PACKAGEFILENAME);
        using (StreamWriter sw = new StreamWriter(zae.Open(), new UTF8Encoding(true)))
        {
           // xml writing code ...
            sw.Write("--snipped--");
        }
    }
}

文件夹APPPACKAGE 包含一些必需的文件。创建 zip 后,我插入我创建的 xml 文件。检查创建的 zip 文件的内容 看起来 正确但接收应用程序无法读取它。我的问题是:有什么我可能错过的吗?

编辑:客户几​​乎没有给我额外的反馈。唯一提到的是,如果出现 md5 错误,可能会发生读取包的错误。我现在怀疑它可能与我创建包的顺序有关。我将尝试先创建 xml 文件,然后创建 zip 文件

【问题讨论】:

  • 什么是“收件人申请”?
  • @LukaszSzczygielek 我将 zip 文件发送到 REST Api。 “接收者应用程序”是我无法控制的应用程序,位于 REST 端点后面。
  • 你有没有问过客户他在他的 REST Api 中看到了什么样的错误?你有他的日志吗?这将有助于调查。您也可以尝试准备 zip 文件,但使用上下文菜单中的 Windows 内置功能并将其发送到 REST Api 以确保您的程序中是否确实存在问题。
  • 好点!我就是这么问的。在我得到响应之前,我得到的唯一线索是,当手动将文件放入 zip 文件时,应用程序会接受我的文件。
  • 也许您的问题与此有关 - stackoverflow.com/questions/20864039/…

标签: c# .net compression


【解决方案1】:

虽然 LukaszSzczygielek 指出 another possible Issue in zip file creation 我的特殊问题的解决方案是首先创建文件然后创建包:

using System.IO;
using System.IO.Compression;

const string ZIPPATH = @".\stock.zip";
const string PACKAGEPATH = @".\stock\content";
const string APPPACKAGE = @".\stock";
const string PACKAGEFILENAME = @"\Offers.xml";

private void CreateZipArchive()
{
    if (!Directory.Exists(PACKAGEPATH)) Directory.CreateDirectory(PACKAGEPATH);

    if (File.Exists(ZIPPATH)) File.Delete(ZIPPATH);

    string fileFullPath = PACKAGEPATH + PACKAGEFILENAME;
    using(Stream fs = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write))
    using(StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(true)))
    {
        // xml writing code ...
        sw.Write("--snipped--");
    }

    ZipFile.CreateFromDirectory(APPPACKAGE, ZIPPATH);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多