0
votes

I have a JSON file created, and I am going to zip it using DotNetZip. Using with StreamWriter to zip it is working, if I try to use MemoryStream it will not working.

StreamWriter :

sw = new StreamWriter(assetsFolder + @"manifest.json");
sw.Write(strManifest);
sw.Close();
zip.AddFile(Path.Combine(assetsFolder, "manifest.json"), "/");
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);

MemoryStream :

var manifestStream = GenerateStreamFromString(strManifest);
public static Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}
zip.AddEntry("manifest.json", manifestStream);  
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);

I must using the .JSON file type to zip it, Can any one told me where have a mistake?

1
That looks correct. Are you sure that your paths are set correctly? - Leon Husmann
If I understand correctly you wanted to gzip your JSON, am I right? - Ali Bahrami
@Leon Husmann Yes the path of assetsFolder is correct, is it zip.AddEntry really create a stream area for saving that json file? - Yuk_dev
@Ali Yes you are right - Yuk_dev
@YukwongTsang yes, it should. May you try this: DotNetZip Examples - Leon Husmann

1 Answers

0
votes

To create a Gzipped Json you need to use GZipStream. Try method below.

https://www.dotnetperls.com/gzipstream

GZipStream compresses data. It saves data efficiently—such as in compressed log files. We develop a utility method in the C# language that uses the System.IO.Compression namespace. It creates GZIP files. It writes them to the disk.

    public static void CompressStringToFile(string fileName, string value)
    {
        // A.
        // Write string to temporary file.
        string temp = Path.GetTempFileName();
        File.WriteAllText(temp, value);

        // B.
        // Read file into byte array buffer.
        byte[] b;
        using (FileStream f = new FileStream(temp, FileMode.Open))
        {
            b = new byte[f.Length];
            f.Read(b, 0, (int)f.Length);
        }

        // C.
        // Use GZipStream to write compressed bytes to target file.
        using (FileStream f2 = new FileStream(fileName, FileMode.Create))
        using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
        {
            gz.Write(b, 0, b.Length);
        }
    }