C#,DataHelper,一个通用的帮助类,留个备份。
1 using System; 2 using Newtonsoft.Json; 3 using System.IO; 4 using System.Text; 5 6 namespace CarHailing.Base 7 { 8 /// <summary> 9 /// 数据帮助类 10 /// </summary> 11 public class DataHelper 12 { 13 /// <summary> 14 /// 英文逗号 15 /// </summary> 16 public const string EnglishComma = ","; 17 18 /// <summary> 19 /// 中文逗号 20 /// </summary> 21 public const string ChineseComma = ","; 22 23 /// <summary> 24 /// 竖线 25 /// </summary> 26 public const string VerticalLine = "|"; 27 28 29 #region 取程序运行所在地址 30 31 /// <summary> 32 /// 取程序运行所在地址 33 /// </summary> 34 /// <returns></returns> 35 public static string GetPath() 36 { 37 string resFilePath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase) 38 + Path.DirectorySeparatorChar; 39 return resFilePath; 40 } 41 42 #endregion 43 44 #region 把对象转换为Json格式 45 /// <summary> 46 /// 把对象转换为Json格式 47 /// </summary> 48 /// <typeparam name="T">对象类型</typeparam> 49 /// <param name="obj">参数</param> 50 /// <returns>加密后字符串</returns> 51 public static string ObjToJson<T>(T obj) 52 { 53 return JsonConvert.SerializeObject(obj); 54 } 55 #endregion 56 57 #region 把Json转换为对象 58 /// <summary> 59 /// 把Json转换为对象 60 /// </summary> 61 /// <typeparam name="T">返回对象类型</typeparam> 62 /// <param name="str">解密字符串</param> 63 /// <returns>解密结果对象</returns> 64 public static T JsonToObj<T>(string str) 65 { 66 return JsonConvert.DeserializeObject<T>(str); 67 } 68 #endregion 69 70 71 #region 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表 72 73 /// <summary> 74 /// 比较普通对象内全部属性,并把修改过的属性的属性值和原属性值存入操作日志表 75 /// 注:现存入操作日志对象的值 为 oldValue | newValue , 如果T1 T2对象位置互换,则为 newValue | oldValue 76 /// </summary> 77 /// <typeparam name="T">普通对象(eg:Line)</typeparam> 78 /// <typeparam name="C">普通对象对应的操作日志对象(eg:LineDoLog)</typeparam> 79 /// <param name="t1">old普通对象</param> 80 /// <param name="t2">修改后的普通对象</param> 81 /// <param name="c1">操作日志对象</param> 82 /// <returns></returns> 83 public static C CompareAndAddLog<T, C>(T t1, T t2) 84 where T : class, new() 85 where C : class, new() 86 { 87 try 88 { 89 C c1 = new C(); 90 System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties(); 91 System.Reflection.PropertyInfo[] logMpi = typeof(C).GetProperties(); 92 93 94 foreach (var pi in mPi) 95 { 96 //比较,只比较值类型 97 if ((pi.PropertyType.IsValueType || pi.PropertyType.Name.StartsWith("String"))) 98 { 99 //string oldValue = pi.GetValue(t1, null).ToString(); 100 //string newValue = pi.GetValue(t2, null).ToString(); 101 102 103 //object getOldValue = pi.GetValue(t1, null); 104 //object getNewValue = pi.GetValue(t2, null); 105 //string oldValue = string.Empty; 106 //string newValue = string.Empty; 107 //if (getOldValue != null) 108 //{ 109 // oldValue = getOldValue.ToString(); 110 //} 111 //else 112 //{ 113 // oldValue = ""; 114 //} 115 //if (getNewValue != null) 116 //{ 117 // newValue = getNewValue.ToString(); 118 //} 119 //else 120 //{ 121 // newValue = ""; 122 //} 123 124 object getOldValue = pi.GetValue(t1, null) ?? ""; 125 object getNewValue = pi.GetValue(t2, null) ?? ""; 126 string oldValue = getOldValue.ToString(); 127 string newValue = getNewValue.ToString(); 128 string oldName = pi.Name; 129 if (!oldValue.Equals(newValue)) 130 { 131 string s = oldValue + "|" + newValue; 132 foreach (var p in logMpi) 133 { 134 if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String"))) 135 { 136 string logDoName = p.Name; 137 if (logDoName.Equals(oldName)) 138 { 139 p.SetValue(c1, s); 140 //p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null); 141 break; 142 } 143 } 144 145 } 146 } 147 else 148 { 149 foreach (var p in logMpi) 150 { 151 if ((p.PropertyType.IsValueType || p.PropertyType.Name.StartsWith("String"))) 152 { 153 string logDoName = p.Name; 154 if (logDoName.Equals(oldName)) 155 { 156 p.SetValue(c1, oldValue); 157 //p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null); 158 break; 159 } 160 } 161 162 } 163 } 164 } 165 166 } 167 return c1; 168 } 169 catch (Exception ex) 170 { 171 throw ex; 172 //return null; 173 } 174 } 175 //for (int i = 0; i < mPi.Length; i++) 176 //{ 177 // System.Reflection.PropertyInfo pi = mPi[i]; 178 179 // string oldValue = pi.GetValue(t1, null).ToString(); 180 // string newValue = pi.GetValue(t2, null).ToString(); 181 // string oldName = pi.Name; 182 // if (!oldValue.Equals(newValue)) 183 // { 184 // string s = oldValue + "|" + newValue; 185 // //pi.SetValue(emptyLine, s); 186 // for (int n = 0; n < logMpi.Length; n++) 187 // { 188 // System.Reflection.PropertyInfo p = logMpi[n]; 189 // string logDoName = p.Name; 190 // if (logDoName.Equals(oldName)) 191 // { 192 // //p.SetValue(emptyLineDoLog, s); 193 // p.SetValue(c1, Convert.ChangeType(s, p.PropertyType), null); 194 // } 195 // } 196 // } 197 // else 198 // { 199 // for (int n = 0; n < logMpi.Length; n++) 200 // { 201 // System.Reflection.PropertyInfo p = logMpi[n]; 202 // string logDoName = p.Name; 203 // if (logDoName.Equals(oldName)) 204 // { 205 // //p.SetValue(emptyLineDoLog, oldValue); 206 // p.SetValue(c1, Convert.ChangeType("", p.PropertyType), null); 207 // } 208 // } 209 // } 210 //} 211 #endregion 212 213 214 #region 对象间赋值 215 216 /// <summary> 217 /// 对象间赋值 218 /// </summary> 219 /// 部分类型不能进行强制转换、名称必须一致且所有子集合间及父集合间名称不能重复 220 /// <typeparam name="T">传入对象</typeparam> 221 /// <typeparam name="L">输出对象</typeparam> 222 /// <param name="t">传入数据</param> 223 /// <returns></returns> 224 public static L Mapper<T, L>(T t) where L : new() 225 { 226 if (t == null) 227 { 228 return default(L); 229 } 230 System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties();//GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); 231 System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties(); 232 L setT = new L(); 233 foreach (System.Reflection.PropertyInfo itemL in propertiesL) 234 { 235 foreach (System.Reflection.PropertyInfo itemT in propertiesT) 236 { 237 if (itemL.Name == itemT.Name) 238 { 239 object value = itemT.GetValue(t, null); 240 itemL.SetValue(setT, value, null); 241 } 242 } 243 } 244 return setT; 245 } 246 #endregion 247 248 #region 获取随机字符串 249 250 /// <summary> 251 /// 获取随机字符串 252 /// </summary> 253 /// <param name="strLength">字符串长度</param> 254 /// <param name="Seed">随机函数种子值</param> 255 /// <returns>指定长度的随机字符串</returns> 256 public static string GetRandomString(int strLength, params int[] Seed) 257 { 258 string strSep = ","; 259 char[] chrSep = strSep.ToCharArray(); 260 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" 261 + ",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"; 262 string[] aryChar = strChar.Split(chrSep, strChar.Length); 263 string strRandom = string.Empty; 264 Random Rnd; 265 if (Seed != null && Seed.Length > 0) 266 { 267 long tick = DateTime.Now.Ticks; 268 int speed = (int)(tick & 0xffffffffL) | (int)(tick >> 32); 269 Rnd = new Random(speed + Seed[0]); 270 } 271 else 272 { 273 Rnd = new Random(); 274 } 275 //生成随机字符串 276 for (int i = 0; i < strLength; i++) 277 { 278 strRandom += aryChar[Rnd.Next(aryChar.Length)]; 279 } 280 return strRandom; 281 } 282 283 #endregion 284 285 #region base64编码的文本转为图片 286 287 288 /// <summary> 289 /// base64编码的文本 转为 图片 290 /// </summary> 291 /// <param name="basedata">文件流</param> 292 /// <param name="savePath">保存路径</param> 293 /// <param name="name">文件名</param> 294 /// <returns>Ex</returns> 295 public static string Base64StringToImage(string basedata, string savePath, string name) 296 { 297 try 298 { 299 if (!Valid.IsBase64String(basedata)) 300 { 301 LoggerHelper.Error("非base64编码"); 302 throw new NullReferenceException("非base64编码!"); 303 } 304 if (!Directory.Exists(savePath))//地图存放的默认文件夹是否存在 305 { 306 Directory.CreateDirectory(savePath);//不存在则创建 307 } 308 string[] sArray = basedata.Split(','); 309 int i = basedata.IndexOf("/") + 1; 310 int j = basedata.IndexOf(";"); 311 string str = basedata.Substring(i, j - i); 312 string fileName = name + "." + str;//文件名 313 string fileFullPath = Path.Combine(savePath, fileName);//合并路径生成文件存放路径 314 byte[] arr2 = Convert.FromBase64String(sArray[1]); 315 using (MemoryStream ms2 = new MemoryStream(arr2)) 316 { 317 System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2); 318 ////只有把当前的图像复制一份,然后把旧的Dispose掉,那个文件就不被锁住了, 319 ////这样就可以放心覆盖原始文件,否则GDI+一般性错误(A generic error occurred in GDI+) 320 System.Drawing.Bitmap bmpNew = new System.Drawing.Bitmap(bmp2); 321 bmp2.Dispose(); 322 bmp2 = null; 323 324 switch (str) 325 { 326 case "bmp": 327 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Bmp); 328 break; 329 case "emf": 330 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Emf); 331 break; 332 case "exif": 333 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Exif); 334 break; 335 case "gif": 336 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Gif); 337 break; 338 case "icon": 339 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Icon); 340 break; 341 case "jpeg": 342 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg); 343 break; 344 //case "jpg": 345 // bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Jpeg); 346 // break; 347 case "memorybmp": 348 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.MemoryBmp); 349 break; 350 case "png": 351 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Png); 352 break; 353 case "tiff": 354 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Tiff); 355 break; 356 case "wmf": 357 bmpNew.Save(fileFullPath, System.Drawing.Imaging.ImageFormat.Wmf); 358 break; 359 default: 360 LoggerHelper.Error("错误的图片格式!"); 361 throw new Exception("错误的图片格式"); 362 } 363 bmpNew.Dispose(); 364 } 365 return str; 366 } 367 catch (Exception ex) 368 { 369 //string result = "Base64StringToImage 转换失败\nException:" + ex.Message; 370 LoggerHelper.Error("Base64StringToImage 转换失败\nException:", ex); 371 throw ex; 372 } 373 } 374 375 #endregion 376 377 #region 字符串写文件 378 /// <summary> 379 /// 字符串写文件 380 /// </summary> 381 /// <param name="file">文件目录</param> 382 /// <param name="data">数据</param> 383 public static void WriteStream(string file, string data) 384 { 385 FileStream fileStream = new FileStream(file, FileMode.Append); 386 StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8); 387 streamWriter.Write(data + "\r\n"); 388 streamWriter.Flush(); 389 streamWriter.Close(); 390 fileStream.Close(); 391 } 392 /// <summary> 393 /// 字符串写文件 394 /// </summary> 395 /// <param name="file">文件目录</param> 396 /// <param name="data">数据</param> 397 public static void WriteStream(string data) 398 { 399 var file = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase) 400 + Path.DirectorySeparatorChar + "Info.txt"; 401 if (!File.Exists(file)) 402 { 403 FileStream fileStream = new FileStream(file, FileMode.Append); 404 StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8); 405 streamWriter.WriteLine(data + "\r\n"); 406 streamWriter.Flush(); 407 streamWriter.Close(); 408 fileStream.Close(); 409 } 410 else 411 { 412 413 FileStream fileStream = new FileStream(file, FileMode.Append); 414 StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8); 415 streamWriter.WriteLine(data + "\r\n"); 416 streamWriter.Flush(); 417 streamWriter.Close(); 418 fileStream.Close(); 419 } 420 } 421 422 #endregion 423 424 425 #region 取文本右边内容 426 /// <summary> 427 /// 取文本右边内容 428 /// </summary> 429 /// <param name="str">文本</param> 430 /// <param name="s">标识符</param> 431 /// <returns>右边内容</returns> 432 public static string GetRight(string str, string s) 433 { 434 //int start = str.IndexOf(s); 435 int strLength = str.Length; 436 int sLength = s.Length; 437 int start = sLength; 438 int end = strLength - sLength; 439 string temp = str.Substring(start, end); 440 return temp; 441 } 442 #endregion 443 444 445 #region 字符串转首字母大写 446 447 /// <summary> 448 449 /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 450 451 /// </summary> 452 453 /// <param name="CnStr">汉字字符串</param> 454 455 /// <returns>相对应的汉语拼音首字母串</returns> 456 457 public static string GetSpellCode(string CnStr) 458 { 459 460 string strTemp = ""; 461 462 int iLen = CnStr.Length; 463 464 int i = 0; 465 466 for (i = 0; i <= iLen - 1; i++) 467 { 468 469 strTemp += GetCharSpellCode(CnStr.Substring(i, 1)); 470 471 } 472 473 return strTemp; 474 475 } 476 477 /// <summary> 478 /// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母 479 /// </summary> 480 /// <param name="CnChar">单个汉字</param> 481 /// <returns>单个大写字母</returns> 482 483 private static string GetCharSpellCode(string CnChar) 484 { 485 486 long iCnChar; 487 488 byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar); 489 490 //如果是字母,则直接返回 491 492 if (ZW.Length == 1) 493 { 494 495 return CnChar.ToUpper(); 496 497 } 498 499 else 500 { 501 502 // get the array of byte from the single char 503 504 int i1 = (short)(ZW[0]); 505 506 int i2 = (short)(ZW[1]); 507 508 iCnChar = i1 * 256 + i2; 509 510 } 511 512 // iCnChar match the constant 513 514 if ((iCnChar >= 45217) && (iCnChar <= 45252)) 515 { 516 517 return "A"; 518 519 } 520 521 else if ((iCnChar >= 45253) && (iCnChar <= 45760)) 522 { 523 524 return "B"; 525 526 } 527 else if ((iCnChar >= 45761) && (iCnChar <= 46317)) 528 { 529 530 return "C"; 531 532 } 533 else if ((iCnChar >= 46318) && (iCnChar <= 46825)) 534 { 535 536 return "D"; 537 538 } 539 else if ((iCnChar >= 46826) && (iCnChar <= 47009)) 540 { 541 542 return "E"; 543 544 } 545 else if ((iCnChar >= 47010) && (iCnChar <= 47296)) 546 { 547 548 return "F"; 549 550 } 551 else if ((iCnChar >= 47297) && (iCnChar <= 47613)) 552 { 553 554 return "G"; 555 556 } 557 else if ((iCnChar >= 47614) && (iCnChar <= 48118)) 558 { 559 560 return "H"; 561 562 } 563 else if ((iCnChar >= 48119) && (iCnChar <= 49061)) 564 { 565 566 return "J"; 567 568 } 569 else if ((iCnChar >= 49062) && (iCnChar <= 49323)) 570 { 571 572 return "K"; 573 574 } 575 else if ((iCnChar >= 49324) && (iCnChar <= 49895)) 576 { 577 578 return "L"; 579 580 } 581 else if ((iCnChar >= 49896) && (iCnChar <= 50370)) 582 { 583 584 return "M"; 585 586 } 587 else if ((iCnChar >= 50371) && (iCnChar <= 50613)) 588 { 589 590 return "N"; 591 592 } 593 else if ((iCnChar >= 50614) && (iCnChar <= 50621)) 594 { 595 596 return "O"; 597 598 } 599 else if ((iCnChar >= 50622) && (iCnChar <= 50905)) 600 { 601 602 return "P"; 603 604 } 605 else if ((iCnChar >= 50906) && (iCnChar <= 51386)) 606 { 607 608 return "Q"; 609 610 } 611 else if ((iCnChar >= 51387) && (iCnChar <= 51445)) 612 { 613 614 return "R"; 615 616 } 617 else if ((iCnChar >= 51446) && (iCnChar <= 52217)) 618 { 619 620 return "S"; 621 622 } 623 else if ((iCnChar >= 52218) && (iCnChar <= 52697)) 624 { 625 626 return "T"; 627 628 } 629 else if ((iCnChar >= 52698) && (iCnChar <= 52979)) 630 { 631 632 return "W"; 633 634 } 635 else if ((iCnChar >= 52980) && (iCnChar <= 53640)) 636 { 637 638 return "X"; 639 640 } 641 else if ((iCnChar >= 53689) && (iCnChar <= 54480)) 642 { 643 644 return "Y"; 645 646 } 647 else if ((iCnChar >= 54481) && (iCnChar <= 55289)) 648 { 649 650 return "Z"; 651 652 } 653 else 654 655 return ("?"); 656 657 } 658 659 #endregion 660 } 661 }
一份数据帮助类,比较粗超,最后这个方法貌似有点问题,有些字符貌似转不出来(应该是编码区域不对吧),具体我也忘了,路过的各位大佬,有兴趣帮忙指证。qqq。