简体   繁体   English

使用MemoryStream和DotNetZip压缩json文件

[英]Using MemoryStream and DotNetZip to zip a json file

I have a JSON file created, and I am going to zip it using DotNetZip. 我创建了一个JSON文件,并将使用DotNetZip将其压缩。 Using with StreamWriter to zip it is working, if I try to use MemoryStream it will not working. 与StreamWriter一起使用以进行压缩可正常工作,如果我尝试使用MemoryStream,它将无法工作。

StreamWriter : 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 : 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? 我必须使用.JSON文件类型对其进行压缩,有人可以告诉我哪里有错误吗?

To create a Gzipped Json you need to use GZipStream . 要创建Gzipped Json,您需要使用GZipStream Try method below. 请尝试以下方法。

https://www.dotnetperls.com/gzipstream https://www.dotnetperls.com/gzipstream

GZipStream compresses data. GZipStream压缩数据。 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. 我们使用C#语言开发一种使用System.IO.Compression命名空间的实用程序方法。 It creates GZIP files. 它创建GZIP文件。 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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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