C # के साथ संपीड़न / अपघटन स्ट्रिंग


144

मैं नौसिखिया हूँ .net मैं सी # में संपीड़न और विघटन स्ट्रिंग कर रहा हूं। एक XML है और मैं स्ट्रिंग में परिवर्तित कर रहा हूं और उसके बाद मैं संपीड़न और डिकंप्रेसन कर रहा हूं। मेरे कोड में कोई भी संकलन त्रुटि नहीं है सिवाय इसके कि जब मैं अपना कोड हटाता हूं और अपना स्ट्रिंग वापस करता हूं, तो इसका केवल XML का आधा हिस्सा लौटता है।

नीचे मेरा कोड है, कृपया मुझे सही करें जहां मैं गलत हूं।

कोड:

class Program
{
    public static string Zip(string value)
    {
        //Transform string into byte[]  
        byte[] byteArray = new byte[value.Length];
        int indexBA = 0;
        foreach (char item in value.ToCharArray())
        {
            byteArray[indexBA++] = (byte)item;
        }

        //Prepare for compress
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);

        //Compress
        sw.Write(byteArray, 0, byteArray.Length);
        //Close, DO NOT FLUSH cause bytes will go missing...
        sw.Close();

        //Transform byte[] zip data to string
        byteArray = ms.ToArray();
        System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
        foreach (byte item in byteArray)
        {
            sB.Append((char)item);
        }
        ms.Close();
        sw.Dispose();
        ms.Dispose();
        return sB.ToString();
    }

    public static string UnZip(string value)
    {
        //Transform string into byte[]
        byte[] byteArray = new byte[value.Length];
        int indexBA = 0;
        foreach (char item in value.ToCharArray())
        {
            byteArray[indexBA++] = (byte)item;
        }

        //Prepare for decompress
        System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
        System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
            System.IO.Compression.CompressionMode.Decompress);

        //Reset variable to collect uncompressed result
        byteArray = new byte[byteArray.Length];

        //Decompress
        int rByte = sr.Read(byteArray, 0, byteArray.Length);

        //Transform byte[] unzip data to string
        System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
        //Read the number of bytes GZipStream red and do not a for each bytes in
        //resultByteArray;
        for (int i = 0; i < rByte; i++)
        {
            sB.Append((char)byteArray[i]);
        }
        sr.Close();
        ms.Close();
        sr.Dispose();
        ms.Dispose();
        return sB.ToString();
    }

    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load(@"D:\RSP.xml");
        string val = doc.ToString(SaveOptions.DisableFormatting);
        val = Zip(val);
        val = UnZip(val);
    }
} 

मेरा XML आकार 63KB है।


1
मुझे शक है कि UTF8Encoding (या UTF16 या whatnot) और GetBytes / GetString का उपयोग करने पर समस्या "अपने आप ठीक हो जाएगी" । यह कोड को भी सरल करेगा। भी उपयोग करने की सलाह देते हैं using

आप बाइट में ब्रेड को बदल नहीं सकते हैं और आप जैसे उल्टा करते हैं (एक साधारण कास्ट का उपयोग करके)। आपको एक एन्कोडिंग का उपयोग करने की आवश्यकता है, और संपीड़न / अपघटन के लिए एक ही एन्कोडिंग है। नीचे xanatos उत्तर देखें।
साइमन मूरियर

@ नहीं यह नहीं होगा; आप के Encodingआसपास गलत तरीके का उपयोग किया जाएगा । आप का आधार -64 जरूरत यहाँ, प्रति xanatos 'जवाब के रूप में
मार्क Gravell

@Marc Gravell ट्रू, हस्ताक्षर / इरादे के उस हिस्से को याद किया। निश्चित रूप से हस्ताक्षर की मेरी पहली पसंद नहीं है।

जवाबों:


257

किसी स्ट्रिंग को संपीड़ित / कूटने का कोड

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

static void Main(string[] args) {
    byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
    string r2 = Unzip(r1);
}

याद रखें कि Zipरिटर्न ए byte[], जबकि Unzipरिटर्न ए string। यदि आप आपसे एक स्ट्रिंग चाहते हैं, Zipतो Base64 इसे एनकोड कर सकता है (उदाहरण के लिए उपयोग करके Convert.ToBase64String(r1)) ( Zipबहुत ही बाइनरी का परिणाम है! यह ऐसा कुछ नहीं है जिसे आप स्क्रीन पर प्रिंट कर सकते हैं या सीधे XML में लिख सकते हैं)

.NET 4.0 के लिए सुझाए गए संस्करण .NET 2.0 के लिए है MemoryStream.CopyTo

महत्वपूर्ण: संपीड़ित सामग्री आउटपुट स्ट्रीम में नहीं लिखी जा सकती, जब तक GZipStreamकि यह न पता हो कि इसमें सभी इनपुट हैं (यानी, प्रभावी रूप से इसे सभी डेटा की आवश्यकता को संपीड़ित करने के लिए)। आपको किसी भी सुनिश्चित करने की आवश्यकता Dispose()का GZipStreamउत्पादन धारा निरीक्षण से पहले (जैसे, mso.ToArray())। यह using() { }ऊपर ब्लॉक के साथ किया जाता है । ध्यान दें कि GZipStreamअंतरतम ब्लॉक है और इसके बाहर सामग्री पहुँच जाती है। एक ही decompressing के लिए चला जाता है: Dispose()के GZipStreamडेटा का उपयोग करने के लिए प्रयास करने से पहले।


उत्तर के लिए धन्यवाद। जब मैं आपके कोड का उपयोग करता हूं, तो यह मुझे संकलन त्रुटि दे रहा है। "CopyTo () में नाम स्थान या विधानसभा संदर्भ नहीं है।" उसके बाद मैंने Google पर खोज की है और इसे .NET 4 फ्रेमवर्क के CopyTo () भाग में फव्वारा दिया है। लेकिन मैं .net 2.0 और 3.5 फ्रेमवर्क पर काम कर रहा हूं। कृपया मुझे सुझाव दें। :)
मोहित कुमार

मैं सिर्फ इस बात पर जोर देना चाहता हूं कि आउटपुट स्ट्रीम पर ToArray () को कॉल करने से पहले GZipStream को निपटाया जाना चाहिए। मैंने उस बिट को नजरअंदाज कर दिया, लेकिन इससे फर्क पड़ता है!
गीले नूडल्स

1
.net 4.5 पर ज़िप करने का यह सबसे प्रभावी तरीका है?
मॉन्स्टरमोरपीजी

1
ध्यान दें कि यह सरोगेट जोड़े जैसे स्ट्रिंग वाले मामले में विफल रहता है (अनज़िप्ड-स्ट्रिंग! = मूल) string s = "X\uD800Y"। मैंने देखा कि अगर हम UTF7 को एन्कोडिंग बदलते हैं तो यह काम करता है ... लेकिन UTF7 के साथ क्या हमें यकीन है कि सभी वर्णों का प्रतिनिधित्व किया जा सकता है?
DigEmAll

@digEmAll मैं कहूंगा कि यह काम नहीं करता है अगर वहाँ INVALID सरोगेट जोड़े हैं (जैसा कि आपके मामले में है)। UTF8 GetByes रूपांतरण चुपचाप अमान्य सरोगेट जोड़ी को 0xFFFD से बदल देता है।
जनातोस १५'१५

103

इस स्निपेट के अनुसार मैं इस कोड का उपयोग करता हूं और यह ठीक काम कर रहा है:

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

namespace CompressString
{
    internal static class StringCompressor
    {
        /// <summary>
        /// Compresses the string.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static string CompressString(string text)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
            return Convert.ToBase64String(gZipBuffer);
        }

        /// <summary>
        /// Decompresses the string.
        /// </summary>
        /// <param name="compressedText">The compressed text.</param>
        /// <returns></returns>
        public static string DecompressString(string compressedText)
        {
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }
    }
}

2
मैं इस कोड को पोस्ट करने के लिए बस आपको धन्यवाद देना चाहता था। मैंने इसे अपने प्रोजेक्ट में उतार दिया और इसने बिना किसी समस्या के बॉक्स से बाहर काम किया।
बोल्टबिट

3
बॉक्स से बाहर काम कर रहे! मुझे पहले चार बाइट्स के रूप में लंबाई जोड़ने का विचार भी पसंद आया
जस्टडेव

2
यह सबसे अच्छा जवाब है। यह एक जवाब के रूप में चिह्नित किया जाना चाहिए!
एरियान कुसुमवर्धनो

1
@ मैट एक ज़िप फ़ाइल की तरह है - .Png पहले से ही एक संपीड़ित सामग्री है
फ़ुबो

2
उत्तर के रूप में चिह्नित किया गया उत्तर स्थिर नहीं है। यह एक सबसे अच्छा जवाब है।
साड़ी

38

Stream.CopyTo () विधियों के साथ .NET 4.0 (और उच्चतर) के आगमन के साथ, मुझे लगा कि मैं एक अद्यतन दृष्टिकोण पोस्ट करूंगा।

मुझे यह भी लगता है कि बेस वर्ज़न को बेस 64 एनकोडेड स्ट्रिंग्स और रेगुलर वर्जन को कंप्रेस करने के लिए स्व-निहित क्लास के स्पष्ट उदाहरण के रूप में उपयोगी है।

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

स्ट्रिंग संपीड़न और विघटन को जोड़ने के लिए स्ट्रिंग वर्ग का विस्तार करने के लिए विस्तार विधियों तकनीक का उपयोग करके यहां एक और दृष्टिकोण दिया गया है। आप किसी मौजूदा प्रोजेक्ट में नीचे की कक्षा को छोड़ सकते हैं और फिर इस प्रकार उपयोग कर सकते हैं:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

तथा

var decompressedString = compressedString.Decompress();

अर्थात:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

2
Jace: मुझे लगता है कि आप usingMemoryStream इंस्टेंस के लिए स्टेटमेंट मिस कर रहे हैं । और एफ # डेवलपर्स के लिए वहाँ: useकंप्रेसरस्ट्रीम / ToArray()
डिकम्प्रेसरस्ट्रीम

1
क्या GZipStream का उपयोग करना बेहतर होगा क्योंकि यह कुछ अतिरिक्त सत्यापन जोड़ता है? GZipStream या DeflateStream वर्ग?
माइकल फ्रीजिम

2
@ मिचेल फ्रीज़िम मुझे ऐसा लगता नहीं होगा कि वे मेमोरी स्ट्रीम को कंप्रेस और डिकम्प्रेस कर रहे हों। फ़ाइलों के लिए, या अविश्वसनीय परिवहन यह समझ में आता है। मैं कहूंगा कि मेरे विशेष उपयोग के मामले में उच्च गति बहुत ही वांछनीय है इसलिए किसी भी ओवरहेड से मैं बच सकता हूं सभी बेहतर है।
Jace

ठोस। JSON के मेरे 20MB स्ट्रिंग को 4.5MB तक ले गया। Sh
जेम्स एश

1
महान काम करता है, लेकिन आपको उपयोग के बाद मेमोरीस्ट्रीम को निपटाना चाहिए, या @knocte द्वारा सुझाए गए प्रत्येक स्ट्रीम का उपयोग करना चाहिए
सेबस्टियन

8

यह .NET 4.5 और नए के लिए एक अद्यतन संस्करण है जो async / प्रतीक्षा और IEnumerables का उपयोग कर रहा है:

public static class CompressionExtensions
{
    public static async Task<IEnumerable<byte>> Zip(this object obj)
    {
        byte[] bytes = obj.Serialize();

        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
                await msi.CopyToAsync(gs);

            return mso.ToArray().AsEnumerable();
        }
    }

    public static async Task<object> Unzip(this byte[] bytes)
    {
        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(msi, CompressionMode.Decompress))
            {
                // Sync example:
                //gs.CopyTo(mso);

                // Async way (take care of using async keyword on the method definition)
                await gs.CopyToAsync(mso);
            }

            return mso.ToArray().Deserialize();
        }
    }
}

public static class SerializerExtensions
{
    public static byte[] Serialize<T>(this T objectToWrite)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);

            return stream.GetBuffer();
        }
    }

    public static async Task<T> _Deserialize<T>(this byte[] arr)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            await stream.WriteAsync(arr, 0, arr.Length);
            stream.Position = 0;

            return (T)binaryFormatter.Deserialize(stream);
        }
    }

    public static async Task<object> Deserialize(this byte[] arr)
    {
        object obj = await arr._Deserialize<object>();
        return obj;
    }
}

इसके साथ आप BinaryFormatterकेवल स्ट्रिंग्स के बजाय सब कुछ का समर्थन कर सकते हैं।

संपादित करें:

मामले में, आपको ध्यान रखने की आवश्यकता है Encoding, आप बस Convert.ToBase64String (बाइट []) का उपयोग कर सकते हैं ...

यदि आपको एक उदाहरण की आवश्यकता है, तो इस उत्तर पर एक नज़र डालें!


आपको अपना नमूना संपादित करने से पहले स्ट्रीम स्थिति को रीसेट करना होगा। साथ ही, आपकी XML टिप्पणियाँ असंबंधित हैं।
मैग्नस जोहानसन

वर्थ इस काम को देख रहा है लेकिन केवल UTF8- आधारित चीजों के लिए। यदि आप कहते हैं कि, स्ट्रिंग वर्ण मान के लिए स्वीडिश वर्ण जैसे आप इसे क्रमबद्ध / deserializing कर रहे हैं तो यह एक गोल-यात्रा परीक्षण विफल हो जाएगा: /
bc3tech

इस मामले में आप उपयोग कर सकते हैं Convert.ToBase64String(byte[])। कृपया, इस उत्तर को देखें ( stackoverflow.com/a/23908465/3286975 )। आशा करता हूँ की ये काम करेगा!
z3nth10n

6

उन लोगों के लिए जो अभी भी GZip हेडर में जादू नंबर प्राप्त कर रहे हैं, सही नहीं है। सुनिश्चित करें कि आप GZip स्ट्रीम में गुजर रहे हैं। त्रुटि और अगर आपका स्ट्रिंग php का उपयोग करके ज़िप किया गया था तो आपको कुछ ऐसा करने की आवश्यकता होगी:

       public static string decodeDecompress(string originalReceivedSrc) {
        byte[] bytes = Convert.FromBase64String(originalReceivedSrc);

        using (var mem = new MemoryStream()) {
            //the trick is here
            mem.Write(new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
            mem.Write(bytes, 0, bytes.Length);

            mem.Position = 0;

            using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
            using (var reader = new StreamReader(gzip)) {
                return reader.ReadToEnd();
                }
            }
        }

मुझे यह अपवाद मिलता है: अपवाद फेंका गया: System.dll में 'System.IO.InvalidDataException' अतिरिक्त जानकारी: GZip पाद लेख में CRC विघटित डेटा से गणना की गई CRC से मेल नहीं खाता।
Dainius Kreivys
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.