C#,DataHelper,一个通用的帮助类,留个备份。

时间:2022-04-16 20:31:46
 using System;
using Newtonsoft.Json;
using System.IO;
using System.Text; namespace CarHailing.Base
{
/// <summary>
/// 数据帮助类
/// </summary>
public class DataHelper
{
/// <summary>
/// 英文逗号
/// </summary>
public const string EnglishComma = ","; /// <summary>
/// 中文逗号
/// </summary>
public const string ChineseComma = ","; /// <summary>
/// 竖线
/// </summary>
public const string VerticalLine = "|"; #region 取程序运行所在地址 /// <summary>
/// 取程序运行所在地址
/// </summary>
/// <returns></returns>
public static string GetPath()
{
string resFilePath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar;
return resFilePath;
} #endregion #region 把对象转换为Json格式
/// <summary>
/// 把对象转换为Json格式
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">参数</param>
/// <returns>加密后字符串</returns>
public static string ObjToJson<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
#endregion #region 把Json转换为对象
/// <summary>
/// 把Json转换为对象
/// </summary>
/// <typeparam name="T">返回对象类型</typeparam>
/// <param name="str">解密字符串</param>
/// <returns>解密结果对象</returns>
public static T JsonToObj<T>(string str)
{
return JsonConvert.DeserializeObject<T>(str);
}
#endregion #region 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表 /// <summary>
/// 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表
/// 注:现存入操作日志对象的值 为 oldValue | newValue , 如果T1 T2对象位置互换,则为 newValue | oldValue
/// </summary>
/// <typeparam name="T">普通对象(eg:Line)</typeparam>
/// <typeparam name="C">普通对象对应的操作日志对象(eg:LineDoLog)</typeparam>
/// <param name="t1">old普通对象</param>
/// <param name="t2">修改后的普通对象</param>
/// <param name="c1">操作日志对象</param>
/// <returns></returns>
public static C CompareAndAddLog<T, C>(T t1, T t2)
where T : class, new()
where C : class, new()
{
try
{
C c1 = new C();
System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties();
System.Reflection.PropertyInfo[] logMpi = typeof(C).GetProperties(); foreach (var pi in mPi)
{
//比较,只比较值类型
if ((pi.PropertyType.IsValueType || pi.PropertyType.Name.StartsWith("String")))
{
//string oldValue = pi.GetValue(t1, null).ToString();
//string newValue = pi.GetValue(t2, null).ToString(); //object getOldValue = pi.GetValue(t1, null);
//object getNewValue = pi.GetValue(t2, null);
//string oldValue = string.Empty;
//string newValue = string.Empty;
//if (getOldValue != null)
//{
// oldValue = getOldValue.ToString();
//}
//else
//{
// oldValue = "";
//}
//if (getNewValue != null)
//{
// newValue = getNewValue.ToString();
//}
//else
//{
// newValue = "";
//} object getOldValue = pi.GetValue(t1, null) ?? "";
object getNewValue = pi.GetValue(t2, null) ?? "";
string oldValue = getOldValue.ToString();
string newValue = getNewValue.ToString();
string oldName = pi.Name;
if (!oldValue.Equals(newValue))
{
string s = oldValue + "|" + newValue;
foreach (var p in logMpi)
{
if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String")))
{
string logDoName = p.Name;
if (logDoName.Equals(oldName))
{
p.SetValue(c1, s);
//p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null);
break;
}
} }
}
else
{
foreach (var p in logMpi)
{
if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String")))
{
string logDoName = p.Name;
if (logDoName.Equals(oldName))
{
p.SetValue(c1, oldValue);
//p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null);
break;
}
} }
}
} }
return c1;
}
catch (Exception ex)
{
throw ex;
//return null;
}
}
//for (int i = 0; i < mPi.Length; i++)
//{
// System.Reflection.PropertyInfo pi = mPi[i]; // string oldValue = pi.GetValue(t1, null).ToString();
// string newValue = pi.GetValue(t2, null).ToString();
// string oldName = pi.Name;
// if (!oldValue.Equals(newValue))
// {
// string s = oldValue + "|" + newValue;
// //pi.SetValue(emptyLine, s);
// for (int n = 0; n < logMpi.Length; n++)
// {
// System.Reflection.PropertyInfo p = logMpi[n];
// string logDoName = p.Name;
// if (logDoName.Equals(oldName))
// {
// //p.SetValue(emptyLineDoLog, s);
// p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null);
// }
// }
// }
// else
// {
// for (int n = 0; n < logMpi.Length; n++)
// {
// System.Reflection.PropertyInfo p = logMpi[n];
// string logDoName = p.Name;
// if (logDoName.Equals(oldName))
// {
// //p.SetValue(emptyLineDoLog, oldValue);
// p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null);
// }
// }
// }
//}
#endregion #region 对象间赋值 /// <summary>
/// 对象间赋值
/// </summary>
/// 部分类型不能进行强制转换、名称必须一致且所有子集合间及父集合间名称不能重复
/// <typeparam name="T">传入对象</typeparam>
/// <typeparam name="L">输出对象</typeparam>
/// <param name="t">传入数据</param>
/// <returns></returns>
public static L Mapper<T, L>(T t) where L : new()
{
if (t == null)
{
return default(L);
}
System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties();//GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties();
L setT = new L();
foreach (System.Reflection.PropertyInfo itemL in propertiesL)
{
foreach (System.Reflection.PropertyInfo itemT in propertiesT)
{
if (itemL.Name == itemT.Name)
{
object value = itemT.GetValue(t, null);
itemL.SetValue(setT, value, null);
}
}
}
return setT;
}
#endregion #region 获取随机字符串 /// <summary>
/// 获取随机字符串
/// </summary>
/// <param name="strLength">字符串长度</param>
/// <param name="Seed">随机函数种子值</param>
/// <returns>指定长度的随机字符串</returns>
public static string GetRandomString(int strLength, params int[] Seed)
{
string strSep = ",";
char[] chrSep = strSep.ToCharArray();
string strChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
+ ",A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] aryChar = strChar.Split(chrSep, strChar.Length);
string strRandom = string.Empty;
Random Rnd;
if (Seed != null && Seed.Length > )
{
long tick = DateTime.Now.Ticks;
int speed = (int)(tick & 0xffffffffL) | (int)(tick >> );
Rnd = new Random(speed + Seed[]);
}
else
{
Rnd = new Random();
}
//生成随机字符串
for (int i = ; i < strLength; i++)
{
strRandom += aryChar[Rnd.Next(aryChar.Length)];
}
return strRandom;
} #endregion #region base64编码的文本转为图片 /// <summary>
/// base64编码的文本 转为 图片
/// </summary>
/// <param name="basedata">文件流</param>
/// <param name="savePath">保存路径</param>
/// <param name="name">文件名</param>
/// <returns>Ex</returns>
public static string Base64StringToImage(string basedata, string savePath, string name)
{
try
{
if (!Valid.IsBase64String(basedata))
{
LoggerHelper.Error("非base64编码");
throw new NullReferenceException("非base64编码!");
}
if (!Directory.Exists(savePath))//地图存放的默认文件夹是否存在
{
Directory.CreateDirectory(savePath);//不存在则创建
}
string[] sArray = basedata.Split(',');
int i = basedata.IndexOf("/") + ;
int j = basedata.IndexOf(";");
string str = basedata.Substring(i, j - i);
string fileName = name + "." + str;//文件名
string fileFullPath = Path.Combine(savePath, fileName);//合并路径生成文件存放路径
byte[] arr2 = Convert.FromBase64String(sArray[]);
using (MemoryStream ms2 = new MemoryStream(arr2))
{
System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
////只有把当前的图像复制一份,然后把旧的Dispose掉,那个文件就不被锁住了,
////这样就可以放心覆盖原始文件,否则GDI+一般性错误(A generic error occurred in GDI+)
System.Drawing.Bitmap bmpNew = new System.Drawing.Bitmap(bmp2);
bmp2.Dispose();
bmp2 = null; switch (str)
{
case "bmp":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case "emf":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Emf);
break;
case "exif":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Exif);
break;
case "gif":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Gif);
break;
case "icon":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Icon);
break;
case "jpeg":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
//case "jpg":
// bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
// break;
case "memorybmp":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.MemoryBmp);
break;
case "png":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Png);
break;
case "tiff":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Tiff);
break;
case "wmf":
bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Wmf);
break;
default:
LoggerHelper.Error("错误的图片格式!");
throw new Exception("错误的图片格式");
}
bmpNew.Dispose();
}
return str;
}
catch (Exception ex)
{
//string result = "Base64StringToImage 转换失败\nException:" + ex.Message;
LoggerHelper.Error("Base64StringToImage 转换失败\nException:", ex);
throw ex;
}
} #endregion #region 字符串写文件
/// <summary>
/// 字符串写文件
/// </summary>
/// <param name="file">文件目录</param>
/// <param name="data">数据</param>
public static void WriteStream(string file, string data)
{
FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.Write(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
/// <summary>
/// 字符串写文件
/// </summary>
/// <param name="file">文件目录</param>
/// <param name="data">数据</param>
public static void WriteStream(string data)
{
var file = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar + "Info.txt";
if (!File.Exists(file))
{
FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.WriteLine(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
else
{ FileStream fileStream = new FileStream(file, FileMode.Append);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
streamWriter.WriteLine(data + "\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
} #endregion #region 取文本右边内容
/// <summary>
/// 取文本右边内容
/// </summary>
/// <param name="str">文本</param>
/// <param name="s">标识符</param>
/// <returns>右边内容</returns>
public static string GetRight(string str, string s)
{
//int start = str.IndexOf(s);
int strLength = str.Length;
int sLength = s.Length;
int start = sLength;
int end = strLength - sLength;
string temp = str.Substring(start, end);
return temp;
}
#endregion #region 字符串转首字母大写 /// <summary> /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 /// </summary> /// <param name="CnStr">汉字字符串</param> /// <returns>相对应的汉语拼音首字母串</returns> public static string GetSpellCode(string CnStr)
{ string strTemp = ""; int iLen = CnStr.Length; int i = ; for (i = ; i <= iLen - ; i++)
{ strTemp += GetCharSpellCode(CnStr.Substring(i, )); } return strTemp; } /// <summary>
/// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母
/// </summary>
/// <param name="CnChar">单个汉字</param>
/// <returns>单个大写字母</returns> private static string GetCharSpellCode(string CnChar)
{ long iCnChar; byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar); //如果是字母,则直接返回 if (ZW.Length == )
{ return CnChar.ToUpper(); } else
{ // get the array of byte from the single char int i1 = (short)(ZW[]); int i2 = (short)(ZW[]); iCnChar = i1 * + i2; } // iCnChar match the constant if ((iCnChar >= ) && (iCnChar <= ))
{ return "A"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "B"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "C"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "D"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "E"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "F"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "G"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "H"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "J"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "K"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "L"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "M"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "N"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "O"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "P"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Q"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "R"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "S"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "T"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "W"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "X"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Y"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Z"; }
else return ("?"); } #endregion
}
}

一份数据帮助类,比较粗超,最后这个方法貌似有点问题,有些字符貌似转不出来(应该是编码区域不对吧),具体我也忘了,路过的各位大佬,有兴趣帮忙指证。qqq。