1 #if !SILVERLIGHT && !XBOX 2 using System; 3 using System.IO; 4 using System.Text; 5 using ServiceStack.CacheAccess; 6 using ServiceStack.Common.Support; 7 using ServiceStack.Common.Web; 8 using ServiceStack.Text; 9 10 namespace ServiceStack.Common 11 { 12 public static class StreamExtensions 13 { 14 #if !MONOTOUCH 15 /// <summary> 16 /// Compresses the specified text using the default compression method: Deflate 17 /// </summary> 18 /// <param name="text">The text.</param> 19 /// <param name="compressionType">Type of the compression.</param> 20 /// <returns></returns> Compress(this string text, string compressionType)21 public static byte[] Compress(this string text, string compressionType) 22 { 23 if (compressionType == CompressionTypes.Deflate) 24 return Deflate(text); 25 26 if (compressionType == CompressionTypes.GZip) 27 return GZip(text); 28 29 throw new NotSupportedException(compressionType); 30 } 31 32 public static IDeflateProvider DeflateProvider = new NetDeflateProvider(); 33 34 public static IGZipProvider GZipProvider = new NetGZipProvider(); 35 36 /// <summary> 37 /// Decompresses the specified gz buffer using the default compression method: Inflate 38 /// </summary> 39 /// <param name="gzBuffer">The gz buffer.</param> 40 /// <param name="compressionType">Type of the compression.</param> 41 /// <returns></returns> Decompress(this byte[] gzBuffer, string compressionType)42 public static string Decompress(this byte[] gzBuffer, string compressionType) 43 { 44 if (compressionType == CompressionTypes.Deflate) 45 return Inflate(gzBuffer); 46 47 if (compressionType == CompressionTypes.GZip) 48 return GUnzip(gzBuffer); 49 50 throw new NotSupportedException(compressionType); 51 } 52 Deflate(this string text)53 public static byte[] Deflate(this string text) 54 { 55 return DeflateProvider.Deflate(text); 56 } 57 Inflate(this byte[] gzBuffer)58 public static string Inflate(this byte[] gzBuffer) 59 { 60 return DeflateProvider.Inflate(gzBuffer); 61 } 62 GZip(this string text)63 public static byte[] GZip(this string text) 64 { 65 return GZipProvider.GZip(text); 66 } 67 GUnzip(this byte[] gzBuffer)68 public static string GUnzip(this byte[] gzBuffer) 69 { 70 return GZipProvider.GUnzip(gzBuffer); 71 } 72 #endif 73 ToUtf8String(this Stream stream)74 public static string ToUtf8String(this Stream stream) 75 { 76 if (stream == null) throw new ArgumentNullException("stream"); 77 78 using (var reader = new StreamReader(stream, Encoding.UTF8)) 79 { 80 return reader.ReadToEnd(); 81 } 82 } 83 ToBytes(this Stream stream)84 public static byte[] ToBytes(this Stream stream) 85 { 86 if (stream == null) throw new ArgumentNullException("stream"); 87 88 return stream.ReadFully(); 89 } 90 Write(this Stream stream, string text)91 public static void Write(this Stream stream, string text) 92 { 93 var bytes = Encoding.ASCII.GetBytes(text); 94 stream.Write(bytes, 0, bytes.Length); 95 } 96 97 } 98 99 } 100 #endif 101