简体   繁体   中英

zip a file programatically like native send to compressed zip folder

I have to send a zipped file to an external application. Support on the other end says the application fails to read my programatically created file. This is how i create the file:

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--");
        }
    }
}

the folder APPPACKAGE contains some required files. After zip creation I insert my created xml file. inspecting the contents of the created zip file everything looks right yet the recipient application fails to read it. My question is: Is there something I might have missed?

Edit: Client gave me little additional Feedback. The only thing mentioned was that filure to read the package can happen if there is an md5 error. I suspect now that it could be related to the order in which I create the package. I'll try to first create the xml file and then create the zip file

Although LukaszSzczygielek pointed out another possible Issue in zip file creation the solution of my particular problem is to first create the files and then create the package:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM