StringExtension (压缩)

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

namespace Ctrip.Domestic.Adapter.Utility
{
public static class StringExtension
{
public static bool IsCnString(this string str)
{
if (string.IsNullOrEmpty(str))
{
return false;
}

return System.Text.RegularExpressions.Regex.IsMatch(str, @"^[\u4e00-\u9fa5]+$");
}

public static string ToDateTimeStr(this string str)
{
if (!string.IsNullOrEmpty(str))
{
var year = "2015";
var month = "01";
var day = "01";
var hour = "00";
var minute = "00";
var second = "00";

if (str.Length >= 8)
{
year = str.Substring(0, 4);
month = str.Substring(4, 2);
day = str.Substring(6, 2);
}

if (str.Length >= 12)
{
hour = str.Substring(8, 2);
minute = str.Substring(10, 2);
}

if (str.Length == 14)
{
second = str.Substring(12, 2);
}

int parseValue = 0;
if (int.TryParse(year, out parseValue) && int.TryParse(month, out parseValue)
&& int.TryParse(day, out parseValue) && int.TryParse(hour, out parseValue)
&& int.TryParse(minute, out parseValue) && int.TryParse(second, out parseValue))
{
return string.Format("{0}-{1}-{2} {3}:{4}:{5}", year, month, day, hour, minute, second);
}
}


return string.Empty;
}

public static string GetSubstring(this string strValue, int length)
{
if (strValue != null && strValue.Length > length)
{
return strValue.Substring(0, length);
}

return strValue;
}

public static string Compress(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

byte[] inputBytes = Encoding.Default.GetBytes(input);
byte[] result = Compress(inputBytes);
return Convert.ToBase64String(result);
}

public static string CompressUTF8(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] result = Compress(inputBytes);
return Convert.ToBase64String(result);

}
public static string Decompress(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

byte[] inputBytes = Convert.FromBase64String(input);
byte[] depressBytes = Decompress(inputBytes);
return Encoding.Default.GetString(depressBytes);
}

public static byte[] Compress(this byte[] inputBytes)
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress, true))
{
zipStream.Write(inputBytes, 0, inputBytes.Length);
zipStream.Close();
return outStream.ToArray();
}
}
}

public static byte[] Decompress(this byte[] inputBytes)
{

using (MemoryStream inputStream = new MemoryStream(inputBytes))
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.Decompress))
{
zipStream.CopyTo(outStream);
zipStream.Close();
return outStream.ToArray();
}
}

}
}
}
}

posted @ 2016-04-20 14:09  点点-滴滴  阅读(226)  评论(0编辑  收藏  举报