///
/// 数据转化帮助类
///
public class ConvertCommon
{
///
/// Base64 编码
///
///
编码方式
///
要编码的字符串
///
返回编码后的字符串
public static string EncodeBase64(Encoding encode, string source)
{
string result = "";
byte[] bytes = encode.GetBytes(source);
try
{
result = Convert.ToBase64String(bytes);
}
catch
{
result = source;
}
return result;
}
///
/// Base64 解码
///
///
解码方式
///
要解码的字符串
///
返回解码后的字符串
public static string DecodeBase64(Encoding encode, string source)
{
string result = "";
byte[] bytes = Convert.FromBase64String(source);
try
{
result = encode.GetString(bytes);
}
catch
{
result = source;
}
return result;
}
///
/// 将时间转化为13位时间戳
///
///
时间
///
返回结果的时间戳
public static string ConvertTimeTo13Stamp(DateTime time)
{
string result = "";
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
result = t.ToString();
return result;
}
///
/// 将13位时间戳转成时间
///
///
时间戳
///
返回结果的时间
public static DateTime Convert13StampToDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
///
/// 将Json 转成 xml字符串
///
///
///
public static string ConvertJsonToXmlString(string json)
{
string result = "";
XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json, "myroot");
result = ConvertXmlToString(xmlDoc);
return result;
}
///
/// 将 XmlDocument 对象转成 xml字符串
///
///
///
public static string ConvertXmlToString(XmlDocument xmlDoc)
{
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
stream.Position = 0;
string xmlString = sr.ReadToEnd();
sr.Close();
stream.Close();
return xmlString;
}
///
/// 字符串转Unicode
///
///
源字符串
///
Unicode编码后的字符串
public static string ConvertStringToUnicode(string source)
{
var bytes = Encoding.Unicode.GetBytes(source);
var stringBuilder = new StringBuilder();
for (var i = 0; i < bytes.Length; i += 2)
{
stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
}
return stringBuilder.ToString();
}
///
/// Unicode转字符串
///
///
经过Unicode编码的字符串
///
正常字符串
public static string ConvertUnicodeToString(string source)
{
return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(source, x => Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)).ToString());
}
}