Inheritance: InputStream
Example #1
0
		/// <summary>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </summary>
		/// <remarks>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </remarks>
		/// <param name="s">the string to decode</param>
		/// <param name="options">encode options such as URL_SAFE</param>
		/// <returns>the decoded data</returns>
		/// <exception cref="System.IO.IOException">if there is an error</exception>
		/// <exception cref="System.ArgumentNullException">if <tt>s</tt> is null</exception>
		/// <since>1.4</since>
		public static byte[] Decode(string s, int options)
		{
			if (s == null)
			{
				throw new ArgumentNullException("Input string was null.");
			}
			// end if
			byte[] bytes;
			try
			{
				bytes = Sharpen.Runtime.GetBytesForString(s, PreferredEncoding);
			}
			catch (UnsupportedEncodingException)
			{
				// end try
				bytes = Sharpen.Runtime.GetBytesForString(s);
			}
			// end catch
			//</change>
			// Decode
			bytes = Decode(bytes, 0, bytes.Length, options);
			// Check to see if it's gzip-compressed
			// GZIP Magic Two-Byte Number: 0x8b1f (35615)
			bool dontGunzip = (options & DontGunzip) != 0;
			if ((bytes != null) && (bytes.Length >= 4) && (!dontGunzip))
			{
				int head = ((int)bytes[0] & unchecked((int)(0xff))) | ((bytes[1] << 8) & unchecked(
					(int)(0xff00)));
				if (GZIPInputStream.GzipMagic == head)
				{
					ByteArrayInputStream bais = null;
					GZIPInputStream gzis = null;
					ByteArrayOutputStream baos = null;
					byte[] buffer = new byte[2048];
					int length = 0;
					try
					{
						baos = new ByteArrayOutputStream();
						bais = new ByteArrayInputStream(bytes);
						gzis = new GZIPInputStream(bais);
						while ((length = gzis.Read(buffer)) >= 0)
						{
							baos.Write(buffer, 0, length);
						}
						// end while: reading input
						// No error? Get new bytes.
						bytes = baos.ToByteArray();
					}
					catch (IOException e)
					{
						// end try
						Sharpen.Runtime.PrintStackTrace(e);
					}
					finally
					{
						// Just return originally-decoded bytes
						// end catch
						try
						{
							baos.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							gzis.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							bais.Close();
						}
						catch (Exception)
						{
						}
					}
				}
			}
			// end finally
			// end if: gzipped
			// end if: bytes.length >= 2
			return bytes;
		}