SoftBasic.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. namespace SWRIS.Extensions
  11. {
  12. /// <summary>
  13. /// 一个软件基础类,提供常用的一些静态方法,比如字符串转换,字节转换的方法<br />
  14. /// A software-based class that provides some common static methods,Such as string conversion, byte conversion method
  15. /// </summary>
  16. public class SoftBasic
  17. {
  18. #region MD5 Calculate
  19. /// <summary>
  20. /// 获取文件的md5码<br />
  21. /// Get the MD5 code of the file
  22. /// </summary>
  23. /// <param name="filePath">文件的路径,既可以是完整的路径,也可以是相对的路径 -> The path to the file</param>
  24. /// <returns>Md5字符串</returns>
  25. /// <example>
  26. /// 下面举例实现获取一个文件的md5码
  27. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="CalculateFileMD5Example" title="CalculateFileMD5示例" />
  28. /// </example>
  29. public static string CalculateFileMD5(string filePath)
  30. {
  31. string str_md5 = string.Empty;
  32. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  33. {
  34. str_md5 = CalculateStreamMD5(fs);
  35. }
  36. return str_md5;
  37. }
  38. /// <summary>
  39. /// 获取数据流的md5码<br />
  40. /// Get the MD5 code for the data stream
  41. /// </summary>
  42. /// <param name="stream">数据流,可以是内存流,也可以是文件流</param>
  43. /// <returns>Md5字符串</returns>
  44. /// <example>
  45. /// 下面举例实现获取一个流的md5码
  46. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="CalculateStreamMD5Example1" title="CalculateStreamMD5示例" />
  47. /// </example>
  48. public static string CalculateStreamMD5(Stream stream)
  49. {
  50. byte[] bytes_md5 = null;
  51. using (MD5 md5 = new MD5CryptoServiceProvider())
  52. {
  53. bytes_md5 = md5.ComputeHash(stream);
  54. }
  55. return BitConverter.ToString(bytes_md5).Replace("-", "");
  56. }
  57. /// <summary>
  58. /// 获取文本字符串信息的Md5码,编码为UTF8<br />
  59. /// Get the Md5 code of the text string information, using the utf-8 encoding
  60. /// </summary>
  61. /// <param name="data">文本数据信息</param>
  62. /// <returns>Md5字符串</returns>
  63. public static string CalculateStreamMD5(string data) => CalculateStreamMD5(data, Encoding.UTF8);
  64. /// <summary>
  65. /// 获取文本字符串信息的Md5码,使用指定的编码<br />
  66. /// Get the Md5 code of the text string information, using the specified encoding
  67. /// </summary>
  68. /// <param name="data">文本数据信息</param>
  69. /// <param name="encode">编码信息</param>
  70. /// <returns>Md5字符串</returns>
  71. public static string CalculateStreamMD5(string data, Encoding encode)
  72. {
  73. string str_md5 = string.Empty;
  74. using (MD5 md5 = new MD5CryptoServiceProvider())
  75. {
  76. byte[] bytes_md5 = md5.ComputeHash(encode.GetBytes(data));
  77. str_md5 = BitConverter.ToString(bytes_md5).Replace("-", "");
  78. }
  79. return str_md5;
  80. }
  81. #if NET35 || NET451
  82. /// <summary>
  83. /// 获取内存图片的md5码<br />
  84. /// Get the MD5 code of the memory picture
  85. /// </summary>
  86. /// <param name="bitmap">内存图片</param>
  87. /// <returns>Md5字符串</returns>
  88. /// <example>
  89. /// 下面举例实现获取一个图像的md5码
  90. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="CalculateStreamMD5Example2" title="CalculateStreamMD5示例" />
  91. /// </example>
  92. public static string CalculateStreamMD5( Bitmap bitmap )
  93. {
  94. MemoryStream ms = new MemoryStream( );
  95. bitmap.Save( ms, bitmap.RawFormat );
  96. byte[] bytes_md5 = null;
  97. using (MD5 md5 = new MD5CryptoServiceProvider( ))
  98. bytes_md5 = md5.ComputeHash( ms );
  99. ms.Dispose( );
  100. return ByteToHexString( bytes_md5 );
  101. }
  102. #endif
  103. #endregion
  104. #region DataSize Format
  105. /// <summary>
  106. /// 从一个字节大小返回带单位的描述,主要是用于显示操作<br />
  107. /// Returns a description with units from a byte size, mainly for display operations
  108. /// </summary>
  109. /// <param name="size">实际的大小值</param>
  110. /// <returns>最终的字符串值</returns>
  111. /// <example>
  112. /// 比如说我们获取了文件的长度,这个长度可以来自于本地,也可以来自于数据库查询
  113. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetSizeDescriptionExample" title="GetSizeDescription示例" />
  114. /// </example>
  115. public static string GetSizeDescription(long size)
  116. {
  117. if (size < 1000)
  118. {
  119. return size + " B";
  120. }
  121. else if (size < 1000 * 1000)
  122. {
  123. float data = (float)size / 1024;
  124. return data.ToString("F2") + " Kb";
  125. }
  126. else if (size < 1000 * 1000 * 1000)
  127. {
  128. float data = (float)size / 1024 / 1024;
  129. return data.ToString("F2") + " Mb";
  130. }
  131. else
  132. {
  133. float data = (float)size / 1024 / 1024 / 1024;
  134. return data.ToString("F2") + " Gb";
  135. }
  136. }
  137. #endregion
  138. #region Array Format
  139. /// <summary>
  140. /// 将数组格式化为显示的字符串的信息,支持所有的类型对象<br />
  141. /// Formats the array into the displayed string information, supporting all types of objects
  142. /// </summary>
  143. /// <typeparam name="T">数组的类型</typeparam>
  144. /// <param name="array">数组信息</param>
  145. /// <returns>最终显示的信息</returns>
  146. public static string ArrayFormat<T>(T[] array) => ArrayFormat(array, string.Empty);
  147. /// <summary>
  148. /// 将数组格式化为显示的字符串的信息,支持所有的类型对象<br />
  149. /// Formats the array into the displayed string information, supporting all types of objects
  150. /// </summary>
  151. /// <typeparam name="T">数组的类型</typeparam>
  152. /// <param name="array">数组信息</param>
  153. /// <param name="format">格式化的信息</param>
  154. /// <returns>最终显示的信息</returns>
  155. public static string ArrayFormat<T>(T[] array, string format)
  156. {
  157. if (array == null) return "NULL";
  158. StringBuilder sb = new StringBuilder("[");
  159. for (int i = 0; i < array.Length; i++)
  160. {
  161. sb.Append(string.IsNullOrEmpty(format) ? array[i].ToString() : string.Format(format, array[i]));
  162. if (i != array.Length - 1) sb.Append(",");
  163. }
  164. sb.Append("]");
  165. return sb.ToString();
  166. }
  167. /// <summary>
  168. /// 将数组格式化为显示的字符串的信息,支持所有的类型对象<br />
  169. /// Formats the array into the displayed string information, supporting all types of objects
  170. /// </summary>
  171. /// <typeparam name="T">数组的类型</typeparam>
  172. /// <param name="array">数组信息</param>
  173. /// <returns>最终显示的信息</returns>
  174. public static string ArrayFormat<T>(T array) => ArrayFormat(array, string.Empty);
  175. /// <summary>
  176. /// 将数组格式化为显示的字符串的信息,支持所有的类型对象<br />
  177. /// Formats the array into the displayed string information, supporting all types of objects
  178. /// </summary>
  179. /// <typeparam name="T">数组的类型</typeparam>
  180. /// <param name="array">数组信息</param>
  181. /// <param name="format">格式化的信息</param>
  182. /// <returns>最终显示的信息</returns>
  183. public static string ArrayFormat<T>(T array, string format)
  184. {
  185. StringBuilder sb = new StringBuilder("[");
  186. if (array is Array array1)
  187. {
  188. foreach (var item in array1)
  189. {
  190. sb.Append(string.IsNullOrEmpty(format) ? item.ToString() : string.Format(format, item));
  191. sb.Append(",");
  192. }
  193. if (array1.Length > 0 && sb[sb.Length - 1] == ',') sb.Remove(sb.Length - 1, 1);
  194. }
  195. else
  196. {
  197. sb.Append(string.IsNullOrEmpty(format) ? array.ToString() : string.Format(format, array));
  198. }
  199. sb.Append("]");
  200. return sb.ToString();
  201. }
  202. #endregion
  203. #region Array Expand
  204. /// <summary>
  205. /// 一个通用的数组新增个数方法,会自动判断越界情况,越界的情况下,会自动的截断或是填充<br />
  206. /// A common array of new methods, will automatically determine the cross-border situation, in the case of cross-border, will be automatically truncated or filled
  207. /// </summary>
  208. /// <typeparam name="T">数据类型</typeparam>
  209. /// <param name="array">原数据</param>
  210. /// <param name="data">等待新增的数据</param>
  211. /// <param name="max">原数据的最大值</param>
  212. /// <example>
  213. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="AddArrayDataExample" title="AddArrayData示例" />
  214. /// </example>
  215. public static void AddArrayData<T>(ref T[] array, T[] data, int max)
  216. {
  217. if (data == null) return; // 数据为空
  218. if (data.Length == 0) return; // 数据长度为空
  219. if (array.Length == max)
  220. {
  221. Array.Copy(array, data.Length, array, 0, array.Length - data.Length);
  222. Array.Copy(data, 0, array, array.Length - data.Length, data.Length);
  223. }
  224. else
  225. {
  226. if ((array.Length + data.Length) > max)
  227. {
  228. T[] tmp = new T[max];
  229. for (int i = 0; i < (max - data.Length); i++)
  230. {
  231. tmp[i] = array[i + (array.Length - max + data.Length)];
  232. }
  233. for (int i = 0; i < data.Length; i++)
  234. {
  235. tmp[tmp.Length - data.Length + i] = data[i];
  236. }
  237. // 更新数据
  238. array = tmp;
  239. }
  240. else
  241. {
  242. T[] tmp = new T[array.Length + data.Length];
  243. for (int i = 0; i < array.Length; i++)
  244. {
  245. tmp[i] = array[i];
  246. }
  247. for (int i = 0; i < data.Length; i++)
  248. {
  249. tmp[tmp.Length - data.Length + i] = data[i];
  250. }
  251. array = tmp;
  252. }
  253. }
  254. }
  255. /// <summary>
  256. /// 将一个数组进行扩充到指定长度,或是缩短到指定长度<br />
  257. /// Extend an array to a specified length, or shorten to a specified length or fill
  258. /// </summary>
  259. /// <typeparam name="T">数组的类型</typeparam>
  260. /// <param name="data">原先数据的数据</param>
  261. /// <param name="length">新数组的长度</param>
  262. /// <returns>新数组长度信息</returns>
  263. /// <example>
  264. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArrayExpandToLengthExample" title="ArrayExpandToLength示例" />
  265. /// </example>
  266. public static T[] ArrayExpandToLength<T>(T[] data, int length)
  267. {
  268. if (data == null) return new T[length];
  269. if (data.Length == length) return data;
  270. T[] buffer = new T[length];
  271. Array.Copy(data, buffer, Math.Min(data.Length, buffer.Length));
  272. return buffer;
  273. }
  274. /// <summary>
  275. /// 将一个数组进行扩充到偶数长度<br />
  276. /// Extend an array to even lengths
  277. /// </summary>
  278. /// <typeparam name="T">数组的类型</typeparam>
  279. /// <param name="data">原先数据的数据</param>
  280. /// <returns>新数组长度信息</returns>
  281. /// <example>
  282. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArrayExpandToLengthEvenExample" title="ArrayExpandToLengthEven示例" />
  283. /// </example>
  284. public static T[] ArrayExpandToLengthEven<T>(T[] data)
  285. {
  286. if (data == null) return new T[0];
  287. if (data.Length % 2 == 1)
  288. return ArrayExpandToLength(data, data.Length + 1);
  289. else
  290. return data;
  291. }
  292. /// <summary>
  293. /// 将指定的数据按照指定长度进行分割,例如int[10],指定长度4,就分割成int[4],int[4],int[2],然后拼接list<br />
  294. /// Divide the specified data according to the specified length, such as int [10], and specify the length of 4 to divide into int [4], int [4], int [2], and then concatenate the list
  295. /// </summary>
  296. /// <typeparam name="T">数组的类型</typeparam>
  297. /// <param name="array">等待分割的数组</param>
  298. /// <param name="length">指定的长度信息</param>
  299. /// <returns>分割后结果内容</returns>
  300. /// <example>
  301. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArraySplitByLengthExample" title="ArraySplitByLength示例" />
  302. /// </example>
  303. public static List<T[]> ArraySplitByLength<T>(T[] array, int length)
  304. {
  305. if (array == null) return new List<T[]>();
  306. List<T[]> result = new List<T[]>();
  307. int index = 0;
  308. while (index < array.Length)
  309. {
  310. if (index + length < array.Length)
  311. {
  312. T[] tmp = new T[length];
  313. Array.Copy(array, index, tmp, 0, length);
  314. index += length;
  315. result.Add(tmp);
  316. }
  317. else
  318. {
  319. T[] tmp = new T[array.Length - index];
  320. Array.Copy(array, index, tmp, 0, tmp.Length);
  321. index += length;
  322. result.Add(tmp);
  323. }
  324. }
  325. return result;
  326. }
  327. /// <summary>
  328. /// 将整数进行有效的拆分成数组,指定每个元素的最大值<br />
  329. /// Effectively split integers into arrays, specifying the maximum value for each element
  330. /// </summary>
  331. /// <param name="integer">整数信息</param>
  332. /// <param name="everyLength">单个的数组长度</param>
  333. /// <returns>拆分后的数组长度</returns>
  334. /// <example>
  335. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="SplitIntegerToArrayExample" title="SplitIntegerToArray示例" />
  336. /// </example>
  337. public static int[] SplitIntegerToArray(int integer, int everyLength)
  338. {
  339. int[] result = new int[(integer / everyLength) + ((integer % everyLength) == 0 ? 0 : 1)];
  340. for (int i = 0; i < result.Length; i++)
  341. {
  342. if (i == result.Length - 1)
  343. {
  344. result[i] = (integer % everyLength) == 0 ? everyLength : (integer % everyLength);
  345. }
  346. else
  347. {
  348. result[i] = everyLength;
  349. }
  350. }
  351. return result;
  352. }
  353. #endregion
  354. #region Byte Array compare
  355. /// <summary>
  356. /// 判断两个字节的指定部分是否相同<br />
  357. /// Determines whether the specified portion of a two-byte is the same
  358. /// </summary>
  359. /// <param name="b1">第一个字节</param>
  360. /// <param name="start1">第一个字节的起始位置</param>
  361. /// <param name="b2">第二个字节</param>
  362. /// <param name="start2">第二个字节的起始位置</param>
  363. /// <param name="length">校验的长度</param>
  364. /// <returns>返回是否相等</returns>
  365. /// <exception cref="IndexOutOfRangeException"></exception>
  366. /// <example>
  367. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="IsTwoBytesEquelExample1" title="IsTwoBytesEquel示例" />
  368. /// </example>
  369. public static bool IsTwoBytesEquel(byte[] b1, int start1, byte[] b2, int start2, int length)
  370. {
  371. if (b1 == null || b2 == null) return false;
  372. for (int i = 0; i < length; i++)
  373. {
  374. if (b1[i + start1] != b2[i + start2])
  375. {
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. /// <summary>
  382. /// 判断两个字节的指定部分是否相同<br />
  383. /// Determines whether the specified portion of a two-byte is the same
  384. /// </summary>
  385. /// <param name="b1">第一个字节</param>
  386. /// <param name="b2">第二个字节</param>
  387. /// <returns>返回是否相等</returns>
  388. /// <example>
  389. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="IsTwoBytesEquelExample2" title="IsTwoBytesEquel示例" />
  390. /// </example>
  391. public static bool IsTwoBytesEquel(byte[] b1, byte[] b2)
  392. {
  393. if (b1 == null || b2 == null) return false;
  394. if (b1.Length != b2.Length) return false;
  395. return IsTwoBytesEquel(b1, 0, b2, 0, b1.Length);
  396. }
  397. /// <summary>
  398. /// 判断两个数据的令牌是否相等<br />
  399. /// Determines whether the tokens of two data are equal
  400. /// </summary>
  401. /// <param name="head">字节数据</param>
  402. /// <param name="token">GUID数据</param>
  403. /// <returns>返回是否相等</returns>
  404. /// <example>
  405. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="IsTwoTokenEquelExample" title="IsByteTokenEquel示例" />
  406. /// </example>
  407. public static bool IsByteTokenEquel(byte[] head, Guid token) => IsTwoBytesEquel(head, 12, token.ToByteArray(), 0, 16);
  408. /// <summary>
  409. /// 判断两个数据的令牌是否相等<br />
  410. /// Determines whether the tokens of two data are equal
  411. /// </summary>
  412. /// <param name="token1">第一个令牌</param>
  413. /// <param name="token2">第二个令牌</param>
  414. /// <returns>返回是否相等</returns>
  415. public static bool IsTwoTokenEquel(Guid token1, Guid token2) => IsTwoBytesEquel(token1.ToByteArray(), 0, token2.ToByteArray(), 0, 16);
  416. #endregion
  417. #region Enum About
  418. /// <summary>
  419. /// 获取一个枚举类型的所有枚举值,可直接应用于组合框数据<br />
  420. /// Gets all the enumeration values of an enumeration type that can be applied directly to the combo box data
  421. /// </summary>
  422. /// <typeparam name="TEnum">枚举的类型值</typeparam>
  423. /// <returns>枚举值数组</returns>
  424. /// <example>
  425. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetEnumValuesExample" title="GetEnumValues示例" />
  426. /// </example>
  427. public static TEnum[] GetEnumValues<TEnum>() where TEnum : struct => (TEnum[])Enum.GetValues(typeof(TEnum));
  428. /// <summary>
  429. /// 从字符串的枚举值数据转换成真实的枚举值数据<br />
  430. /// Convert enumeration value data from strings to real enumeration value data
  431. /// </summary>
  432. /// <typeparam name="TEnum">枚举的类型值</typeparam>
  433. /// <param name="value">枚举的字符串的数据值</param>
  434. /// <returns>真实的枚举值</returns>
  435. /// <example>
  436. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetEnumFromStringExample" title="GetEnumFromString示例" />
  437. /// </example>
  438. public static TEnum GetEnumFromString<TEnum>(string value) where TEnum : struct => (TEnum)Enum.Parse(typeof(TEnum), value);
  439. #endregion
  440. #region JSON XML Data Get
  441. /// <summary>
  442. /// 一个泛型方法,提供json对象的数据读取<br />
  443. /// A generic method that provides data read for a JSON object
  444. /// </summary>
  445. /// <typeparam name="T">读取的泛型</typeparam>
  446. /// <param name="json">json对象</param>
  447. /// <param name="name">值名称</param>
  448. /// <param name="defaultValue">默认值</param>
  449. /// <returns>值对象</returns>
  450. /// <example>
  451. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetValueFromJsonObjectExample" title="GetValueFromJsonObject示例" />
  452. /// </example>
  453. public static T GetValueFromJsonObject<T>(JObject json, string name, T defaultValue)
  454. {
  455. if (json.Property(name) != null)
  456. {
  457. return json.Property(name).Value.Value<T>();
  458. }
  459. else
  460. {
  461. return defaultValue;
  462. }
  463. }
  464. /// <summary>
  465. /// 一个泛型方法,提供json对象的数据写入<br />
  466. /// A generic method that provides data writing to a JSON object
  467. /// </summary>
  468. /// <typeparam name="T">写入的泛型</typeparam>
  469. /// <param name="json">json对象</param>
  470. /// <param name="property">值名称</param>
  471. /// <param name="value">值数据</param>
  472. /// <example>
  473. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="JsonSetValueExample" title="JsonSetValue示例" />
  474. /// </example>
  475. public static void JsonSetValue<T>(JObject json, string property, T value)
  476. {
  477. if (json.Property(property) != null)
  478. {
  479. json.Property(property).Value = new JValue(value);
  480. }
  481. else
  482. {
  483. json.Add(property, new JValue(value));
  484. }
  485. }
  486. #endregion
  487. /// <summary>
  488. /// 获取一个异常的完整错误信息<br />
  489. /// Gets the complete error message for an exception
  490. /// </summary>
  491. /// <param name="ex">异常对象</param>
  492. /// <returns>完整的字符串数据</returns>
  493. /// <remarks>获取异常的完整信息</remarks>
  494. /// <exception cref="NullReferenceException">ex不能为空</exception>
  495. /// <example>
  496. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetExceptionMessageExample1" title="GetExceptionMessage示例" />
  497. /// </example>
  498. public static string GetExceptionMessage(Exception ex)
  499. {
  500. return "错误信息:" + ex.Message + Environment.NewLine +
  501. "错误堆栈:" + ex.StackTrace + Environment.NewLine +
  502. "错误方法:" + ex.TargetSite;
  503. }
  504. /// <summary>
  505. /// 获取一个异常的完整错误信息,和额外的字符串描述信息<br />
  506. /// Gets the complete error message for an exception, and additional string description information
  507. /// </summary>
  508. /// <param name="extraMsg">额外的信息</param>
  509. /// <param name="ex">异常对象</param>
  510. /// <returns>完整的字符串数据</returns>
  511. /// <exception cref="NullReferenceException"></exception>
  512. /// <example>
  513. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetExceptionMessageExample2" title="GetExceptionMessage示例" />
  514. /// </example>
  515. public static string GetExceptionMessage(string extraMsg, Exception ex)
  516. {
  517. if (string.IsNullOrEmpty(extraMsg))
  518. return GetExceptionMessage(ex);
  519. else
  520. return extraMsg + Environment.NewLine + GetExceptionMessage(ex);
  521. }
  522. #region Hex string and Byte[] transform
  523. /// <summary>
  524. /// 字节数据转化成16进制表示的字符串<br />
  525. /// Byte data into a string of 16 binary representations
  526. /// </summary>
  527. /// <param name="InBytes">字节数组</param>
  528. /// <returns>返回的字符串</returns>
  529. /// <example>
  530. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ByteToHexStringExample1" title="ByteToHexString示例" />
  531. /// </example>
  532. public static string ByteToHexString(byte[] InBytes) => ByteToHexString(InBytes, (char)0);
  533. /// <summary>
  534. /// 字节数据转化成16进制表示的字符串<br />
  535. /// Byte data into a string of 16 binary representations
  536. /// </summary>
  537. /// <param name="InBytes">字节数组</param>
  538. /// <param name="segment">分割符</param>
  539. /// <returns>返回的字符串</returns>
  540. /// <example>
  541. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ByteToHexStringExample2" title="ByteToHexString示例" />
  542. /// </example>
  543. public static string ByteToHexString(byte[] InBytes, char segment) => ByteToHexString(InBytes, segment, 0);
  544. /// <summary>
  545. /// 字节数据转化成16进制表示的字符串<br />
  546. /// Byte data into a string of 16 binary representations
  547. /// </summary>
  548. /// <param name="InBytes">字节数组</param>
  549. /// <param name="segment">分割符,如果设置为0,则没有分隔符信息</param>
  550. /// <param name="newLineCount">每隔指定数量的时候进行换行,如果小于等于0,则不进行分行显示</param>
  551. /// <param name="format">格式信息,默认为{0:X2}</param>
  552. /// <returns>返回的字符串</returns>
  553. /// <example>
  554. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ByteToHexStringExample2" title="ByteToHexString示例" />
  555. /// </example>
  556. public static string ByteToHexString(byte[] InBytes, char segment, int newLineCount, string format = "{0:X2}")
  557. {
  558. if (InBytes == null) return string.Empty;
  559. StringBuilder sb = new StringBuilder();
  560. long tick = 0;
  561. foreach (byte InByte in InBytes)
  562. {
  563. if (segment == 0) sb.Append(string.Format(format, InByte));
  564. else sb.Append(string.Format(format + "{1}", InByte, segment));
  565. tick++;
  566. if (newLineCount > 0 && tick >= newLineCount)
  567. {
  568. sb.Append(Environment.NewLine);
  569. tick = 0;
  570. }
  571. }
  572. if (segment != 0 && sb.Length > 1 && sb[sb.Length - 1] == segment)
  573. {
  574. sb.Remove(sb.Length - 1, 1);
  575. }
  576. return sb.ToString();
  577. }
  578. /// <summary>
  579. /// 字符串数据转化成16进制表示的字符串<br />
  580. /// String data into a string of 16 binary representations
  581. /// </summary>
  582. /// <param name="InString">输入的字符串数据</param>
  583. /// <returns>返回的字符串</returns>
  584. /// <exception cref="NullReferenceException"></exception>
  585. public static string ByteToHexString(string InString) => ByteToHexString(Encoding.Unicode.GetBytes(InString));
  586. private static int GetHexCharIndex(char ch)
  587. {
  588. switch (ch)
  589. {
  590. case '0': return 0;
  591. case '1': return 1;
  592. case '2': return 2;
  593. case '3': return 3;
  594. case '4': return 4;
  595. case '5': return 5;
  596. case '6': return 6;
  597. case '7': return 7;
  598. case '8': return 8;
  599. case '9': return 9;
  600. case 'A':
  601. case 'a': return 10;
  602. case 'B':
  603. case 'b': return 11;
  604. case 'C':
  605. case 'c': return 12;
  606. case 'D':
  607. case 'd': return 13;
  608. case 'E':
  609. case 'e': return 14;
  610. case 'F':
  611. case 'f': return 15;
  612. default: return -1;
  613. }
  614. }
  615. /// <summary>
  616. /// 将16进制的字符串转化成Byte数据,将检测每2个字符转化,也就是说,中间可以是任意字符<br />
  617. /// Converts a 16-character string into byte data, which will detect every 2 characters converted, that is, the middle can be any character
  618. /// </summary>
  619. /// <param name="hex">十六进制的字符串,中间可以是任意的分隔符</param>
  620. /// <returns>转换后的字节数组</returns>
  621. /// <remarks>参数举例:AA 01 34 A8</remarks>
  622. /// <example>
  623. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="HexStringToBytesExample" title="HexStringToBytes示例" />
  624. /// </example>
  625. public static byte[] HexStringToBytes(string hex)
  626. {
  627. MemoryStream ms = new MemoryStream();
  628. for (int i = 0; i < hex.Length; i++)
  629. {
  630. if ((i + 1) < hex.Length)
  631. {
  632. if (GetHexCharIndex(hex[i]) >= 0 && GetHexCharIndex(hex[i + 1]) >= 0)
  633. {
  634. // 这是一个合格的字节数据
  635. ms.WriteByte((byte)(GetHexCharIndex(hex[i]) * 16 + GetHexCharIndex(hex[i + 1])));
  636. i++;
  637. }
  638. }
  639. }
  640. byte[] result = ms.ToArray();
  641. ms.Dispose();
  642. return result;
  643. }
  644. #endregion
  645. #region Byte Reverse By Word
  646. /// <summary>
  647. /// 将byte数组按照双字节进行反转,如果为单数的情况,则自动补齐<br />
  648. /// Reverses the byte array by double byte, or if the singular is the case, automatically
  649. /// </summary>
  650. /// <remarks>
  651. /// 例如传入的字节数据是 01 02 03 04, 那么反转后就是 02 01 04 03
  652. /// </remarks>
  653. /// <param name="inBytes">输入的字节信息</param>
  654. /// <returns>反转后的数据</returns>
  655. /// <example>
  656. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="BytesReverseByWord" title="BytesReverseByWord示例" />
  657. /// </example>
  658. public static byte[] BytesReverseByWord(byte[] inBytes)
  659. {
  660. if (inBytes == null) return null;
  661. if (inBytes.Length == 0) return new byte[0];
  662. byte[] buffer = ArrayExpandToLengthEven(CopyArray(inBytes));
  663. for (int i = 0; i < buffer.Length / 2; i++)
  664. {
  665. byte tmp = buffer[i * 2 + 0];
  666. buffer[i * 2 + 0] = buffer[i * 2 + 1];
  667. buffer[i * 2 + 1] = tmp;
  668. }
  669. return buffer;
  670. }
  671. /// <summary>
  672. /// 拷贝当前的实例数组,是基于引用层的浅拷贝,如果类型为值类型,那就是深度拷贝,如果类型为引用类型,就是浅拷贝
  673. /// </summary>
  674. /// <typeparam name="T">类型对象</typeparam>
  675. /// <param name="value">数组对象</param>
  676. /// <returns>拷贝的结果内容</returns>
  677. public static T[] CopyArray<T>(T[] value)
  678. {
  679. if (value == null) return null;
  680. T[] buffer = new T[value.Length];
  681. Array.Copy(value, buffer, value.Length);
  682. return buffer;
  683. }
  684. #endregion
  685. #region Byte[] and AsciiByte[] transform
  686. /// <summary>
  687. /// 将字节数组显示为ASCII格式的字符串,当遇到0x20以下及0x7E以上的不可见字符时,使用十六进制的数据显示<br />
  688. /// Display the byte array as a string in ASCII format, when encountering invisible characters below 0x20 and above 0x7E, use hexadecimal data to display<br />
  689. /// </summary>
  690. /// <param name="content">字节数组信息</param>
  691. /// <returns>ASCII格式的字符串信息</returns>
  692. public static string GetAsciiStringRender(byte[] content)
  693. {
  694. if (content == null) return string.Empty;
  695. StringBuilder sb = new StringBuilder();
  696. for (int i = 0; i < content.Length; i++)
  697. {
  698. if (content[i] < 0x20 || content[i] > 0x7E)
  699. {
  700. sb.Append($"\\{content[i]:X2}");
  701. }
  702. else
  703. {
  704. sb.Append((char)content[i]);
  705. }
  706. }
  707. return sb.ToString();
  708. }
  709. /// <summary>
  710. /// 从显示的ASCII格式的字符串,转为原始字节数组,如果遇到 \00 这种表示原始字节的内容,则直接进行转换操作,遇到 \r 直接转换 0x0D, \n 直接转换 0x0A<br />
  711. /// Convert from the displayed string in ASCII format to the original byte array. If you encounter \00, which represents the original byte content,
  712. /// the conversion operation is performed directly. When encountering \r, it is directly converted to 0x0D, and \n is directly converted to 0x0A.
  713. /// </summary>
  714. /// <param name="render">等待转换的字符串</param>
  715. /// <returns>原始字节数组</returns>
  716. public static byte[] GetFromAsciiStringRender(string render)
  717. {
  718. if (string.IsNullOrEmpty(render)) return new byte[0];
  719. MatchEvaluator matchEvaluator = new MatchEvaluator(m => string.Format("{0}", (char)Convert.ToByte(m.Value.Substring(1), 16)));
  720. return Encoding.ASCII.GetBytes(Regex.Replace(render.Replace("\\r", "\r").Replace("\\n", "\n"), @"\\[0-9A-Fa-f]{2}", matchEvaluator));
  721. }
  722. /// <summary>
  723. /// 将原始的byte数组转换成ascii格式的byte数组<br />
  724. /// Converts the original byte array to an ASCII-formatted byte array
  725. /// </summary>
  726. /// <param name="inBytes">等待转换的byte数组</param>
  727. /// <returns>转换后的数组</returns>
  728. public static byte[] BytesToAsciiBytes(byte[] inBytes) => Encoding.ASCII.GetBytes(ByteToHexString(inBytes));
  729. /// <summary>
  730. /// 将ascii格式的byte数组转换成原始的byte数组<br />
  731. /// Converts an ASCII-formatted byte array to the original byte array
  732. /// </summary>
  733. /// <param name="inBytes">等待转换的byte数组</param>
  734. /// <returns>转换后的数组</returns>
  735. public static byte[] AsciiBytesToBytes(byte[] inBytes) => HexStringToBytes(Encoding.ASCII.GetString(inBytes));
  736. /// <summary>
  737. /// 从字节构建一个ASCII格式的数据内容<br />
  738. /// Build an ASCII-formatted data content from bytes
  739. /// </summary>
  740. /// <param name="value">数据</param>
  741. /// <returns>ASCII格式的字节数组</returns>
  742. public static byte[] BuildAsciiBytesFrom(byte value) => Encoding.ASCII.GetBytes(value.ToString("X2"));
  743. /// <summary>
  744. /// 从short构建一个ASCII格式的数据内容<br />
  745. /// Constructing an ASCII-formatted data content from a short
  746. /// </summary>
  747. /// <param name="value">数据</param>
  748. /// <returns>ASCII格式的字节数组</returns>
  749. public static byte[] BuildAsciiBytesFrom(short value) => Encoding.ASCII.GetBytes(value.ToString("X4"));
  750. /// <summary>
  751. /// 从ushort构建一个ASCII格式的数据内容<br />
  752. /// Constructing an ASCII-formatted data content from ushort
  753. /// </summary>
  754. /// <param name="value">数据</param>
  755. /// <returns>ASCII格式的字节数组</returns>
  756. public static byte[] BuildAsciiBytesFrom(ushort value) => Encoding.ASCII.GetBytes(value.ToString("X4"));
  757. /// <summary>
  758. /// 从uint构建一个ASCII格式的数据内容<br />
  759. /// Constructing an ASCII-formatted data content from uint
  760. /// </summary>
  761. /// <param name="value">数据</param>
  762. /// <returns>ASCII格式的字节数组</returns>
  763. public static byte[] BuildAsciiBytesFrom(uint value) => Encoding.ASCII.GetBytes(value.ToString("X8"));
  764. /// <summary>
  765. /// 从字节数组构建一个ASCII格式的数据内容<br />
  766. /// Byte array to construct an ASCII format data content
  767. /// </summary>
  768. /// <param name="value">字节信息</param>
  769. /// <returns>ASCII格式的地址</returns>
  770. public static byte[] BuildAsciiBytesFrom(byte[] value)
  771. {
  772. byte[] buffer = new byte[value.Length * 2];
  773. for (int i = 0; i < value.Length; i++)
  774. {
  775. SoftBasic.BuildAsciiBytesFrom(value[i]).CopyTo(buffer, 2 * i);
  776. }
  777. return buffer;
  778. }
  779. #endregion
  780. #region Bool and Byte transform
  781. private static byte GetDataByBitIndex(int offset)
  782. {
  783. switch (offset)
  784. {
  785. case 0: return 0x01;
  786. case 1: return 0x02;
  787. case 2: return 0x04;
  788. case 3: return 0x08;
  789. case 4: return 0x10;
  790. case 5: return 0x20;
  791. case 6: return 0x40;
  792. case 7: return 0x80;
  793. default: return 0;
  794. }
  795. }
  796. /// <summary>
  797. /// 获取byte数据类型的第offset位,是否为True<br />
  798. /// Gets the index bit of the byte data type, whether it is True
  799. /// </summary>
  800. /// <param name="value">byte数值</param>
  801. /// <param name="offset">索引位置</param>
  802. /// <returns>结果</returns>
  803. /// <example>
  804. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="BoolOnByteIndex" title="BoolOnByteIndex示例" />
  805. /// </example>
  806. public static bool BoolOnByteIndex(byte value, int offset)
  807. {
  808. byte temp = GetDataByBitIndex(offset);
  809. return (value & temp) == temp;
  810. }
  811. /// <summary>
  812. /// 设置取byte数据类型的第offset位,是否为True<br />
  813. /// Set the offset bit of the byte data type, whether it is True
  814. /// </summary>
  815. /// <param name="byt">byte数值</param>
  816. /// <param name="offset">索引位置</param>
  817. /// <param name="value">写入的结果值</param>
  818. /// <returns>结果</returns>
  819. /// <example>
  820. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="SetBoolOnByteIndex" title="SetBoolOnByteIndex示例" />
  821. /// </example>
  822. public static byte SetBoolOnByteIndex(byte byt, int offset, bool value)
  823. {
  824. byte temp = GetDataByBitIndex(offset);
  825. if (value) return (byte)(byt | temp);
  826. return (byte)(byt & (~temp));
  827. }
  828. /// <summary>
  829. /// 将bool数组转换到byte数组<br />
  830. /// Converting a bool array to a byte array
  831. /// </summary>
  832. /// <param name="array">bool数组</param>
  833. /// <returns>转换后的字节数组</returns>
  834. /// <example>
  835. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="BoolArrayToByte" title="BoolArrayToByte示例" />
  836. /// </example>
  837. public static byte[] BoolArrayToByte(bool[] array)
  838. {
  839. if (array == null) return null;
  840. int length = array.Length % 8 == 0 ? array.Length / 8 : array.Length / 8 + 1;
  841. byte[] buffer = new byte[length];
  842. for (int i = 0; i < array.Length; i++)
  843. {
  844. if (array[i]) buffer[i / 8] += GetDataByBitIndex(i % 8);
  845. }
  846. return buffer;
  847. }
  848. /// <summary>
  849. /// 将bool数组转换为字符串进行显示,true被转为1,false转换为0<br />
  850. /// Convert the bool array to a string for display, true is converted to 1, false is converted to 0
  851. /// </summary>
  852. /// <param name="array">bool数组</param>
  853. /// <returns>转换后的字符串</returns>
  854. public static string BoolArrayToString(bool[] array)
  855. {
  856. if (array == null) return string.Empty;
  857. StringBuilder sb = new StringBuilder();
  858. for (int i = 0; i < array.Length; i++)
  859. {
  860. sb.Append(array[i] ? "1" : "0");
  861. }
  862. return sb.ToString();
  863. }
  864. /// <summary>
  865. /// 从Byte数组中提取位数组,length代表位数,例如数组 03 A1 长度10转为 [1100 0000 10]<br />
  866. /// Extracts a bit array from a byte array, length represents the number of digits
  867. /// </summary>
  868. /// <param name="inBytes">原先的字节数组</param>
  869. /// <param name="length">想要转换的长度,如果超出自动会缩小到数组最大长度</param>
  870. /// <returns>转换后的bool数组</returns>
  871. /// <example>
  872. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ByteToBoolArray" title="ByteToBoolArray示例" />
  873. /// </example>
  874. public static bool[] ByteToBoolArray(byte[] inBytes, int length)
  875. {
  876. if (inBytes == null) return null;
  877. if (length > inBytes.Length * 8) length = inBytes.Length * 8;
  878. bool[] buffer = new bool[length];
  879. for (int i = 0; i < length; i++)
  880. {
  881. buffer[i] = BoolOnByteIndex(inBytes[i / 8], i % 8);
  882. }
  883. return buffer;
  884. }
  885. /// <summary>
  886. /// 从Byte数组中提取位数组,length代表位数,例如数组 01 00 长度10转为 [true,false]<br />
  887. /// </summary>
  888. /// <param name="inBytes">原先的字节数组</param>
  889. /// <param name="length">想要转换的长度,如果超出自动会缩小到数组最大长度</param>
  890. /// <param name="trueValue">当为true时对应的byte值</param>
  891. /// <returns>转换后bool数组</returns>
  892. public static bool[] ByteToBoolArray(byte[] inBytes, int length, byte trueValue)
  893. {
  894. if (inBytes == null) return null;
  895. if (length > inBytes.Length) length = inBytes.Length;
  896. bool[] buffer = new bool[length];
  897. for (int i = 0; i < length; i++)
  898. {
  899. buffer[i] = inBytes[i] == trueValue;
  900. }
  901. return buffer;
  902. }
  903. /// <summary>
  904. /// 从Byte数组中提取所有的位数组<br />
  905. /// Extracts a bit array from a byte array, length represents the number of digits
  906. /// </summary>
  907. /// <param name="InBytes">原先的字节数组</param>
  908. /// <returns>转换后的bool数组</returns>
  909. /// <example>
  910. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ByteToBoolArray" title="ByteToBoolArray示例" />
  911. /// </example>
  912. public static bool[] ByteToBoolArray(byte[] InBytes) => InBytes == null ? null : ByteToBoolArray(InBytes, InBytes.Length * 8);
  913. #endregion
  914. #region Array Clip
  915. /// <summary>
  916. /// 将一个数组的前后移除指定位数,返回新的一个数组<br/>
  917. /// Removes a array before and after the specified number of bits, returning a new array
  918. /// </summary>
  919. /// <param name="value">数组</param>
  920. /// <param name="leftLength">前面的位数</param>
  921. /// <param name="rightLength">后面的位数</param>
  922. /// <returns>新的数组</returns>
  923. /// <exception cref="RankException"></exception>
  924. /// <example>
  925. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArrayRemoveDouble" title="ArrayRemoveDouble示例" />
  926. /// </example>
  927. public static T[] ArrayRemoveDouble<T>(T[] value, int leftLength, int rightLength)
  928. {
  929. if (value == null) return null;
  930. if (value.Length <= (leftLength + rightLength)) return new T[0];
  931. T[] buffer = new T[value.Length - leftLength - rightLength];
  932. Array.Copy(value, leftLength, buffer, 0, buffer.Length);
  933. return buffer;
  934. }
  935. /// <summary>
  936. /// 将一个数组的前面指定位数移除,返回新的一个数组<br />
  937. /// Removes the preceding specified number of bits in a array, returning a new array
  938. /// </summary>
  939. /// <param name="value">数组</param>
  940. /// <param name="length">等待移除的长度</param>
  941. /// <returns>新的数组</returns>
  942. /// <exception cref="RankException"></exception>
  943. /// <example>
  944. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArrayRemoveBegin" title="ArrayRemoveBegin示例" />
  945. /// </example>
  946. public static T[] ArrayRemoveBegin<T>(T[] value, int length) => ArrayRemoveDouble(value, length, 0);
  947. /// <summary>
  948. /// 将一个数组的后面指定位数移除,返回新的一个数组<br />
  949. /// Removes the specified number of digits after a array, returning a new array
  950. /// </summary>
  951. /// <param name="value">数组</param>
  952. /// <param name="length">等待移除的长度</param>
  953. /// <returns>新的数组</returns>
  954. /// <exception cref="RankException"></exception>
  955. /// <example>
  956. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArrayRemoveLast" title="ArrayRemoveLast示例" />
  957. /// </example>
  958. public static T[] ArrayRemoveLast<T>(T[] value, int length) => ArrayRemoveDouble(value, 0, length);
  959. /// <summary>
  960. /// 获取到数组里面的中间指定长度的数组<br />
  961. /// Get an array of the specified length in the array
  962. /// </summary>
  963. /// <param name="value">数组</param>
  964. /// <param name="index">起始索引</param>
  965. /// <param name="length">数据的长度</param>
  966. /// <returns>新的数组值</returns>
  967. /// <exception cref="IndexOutOfRangeException"></exception>
  968. /// <example>
  969. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArraySelectMiddle" title="ArraySelectMiddle示例" />
  970. /// </example>
  971. public static T[] ArraySelectMiddle<T>(T[] value, int index, int length)
  972. {
  973. if (value == null) return null;
  974. if (length == 0) return new T[0];
  975. T[] buffer = new T[Math.Min(value.Length, length)];
  976. Array.Copy(value, index, buffer, 0, buffer.Length);
  977. return buffer;
  978. }
  979. /// <summary>
  980. /// 选择一个数组的前面的几个数据信息<br />
  981. /// Select the begin few items of data information of a array
  982. /// </summary>
  983. /// <param name="value">数组</param>
  984. /// <param name="length">数据的长度</param>
  985. /// <returns>新的数组</returns>
  986. /// <example>
  987. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArraySelectBegin" title="ArraySelectBegin示例" />
  988. /// </example>
  989. public static T[] ArraySelectBegin<T>(T[] value, int length)
  990. {
  991. if (length == 0) return new T[0];
  992. T[] buffer = new T[Math.Min(value.Length, length)];
  993. if (buffer.Length > 0) Array.Copy(value, 0, buffer, 0, buffer.Length);
  994. return buffer;
  995. }
  996. /// <summary>
  997. /// 选择一个数组的后面的几个数据信息<br />
  998. /// Select the last few items of data information of a array
  999. /// </summary>
  1000. /// <param name="value">数组</param>
  1001. /// <param name="length">数据的长度</param>
  1002. /// <returns>新的数组信息</returns>
  1003. /// <example>
  1004. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="ArraySelectLast" title="ArraySelectLast示例" />
  1005. /// </example>
  1006. public static T[] ArraySelectLast<T>(T[] value, int length)
  1007. {
  1008. if (length == 0) return new T[0];
  1009. T[] buffer = new T[Math.Min(value.Length, length)];
  1010. Array.Copy(value, value.Length - length, buffer, 0, buffer.Length);
  1011. return buffer;
  1012. }
  1013. #endregion
  1014. #region Byte[] Splice
  1015. /// <summary>
  1016. /// 拼接任意个泛型数组为一个总的泛型数组对象,采用深度拷贝实现。<br />
  1017. /// Splicing any number of generic arrays into a total generic array object is implemented using deep copy.
  1018. /// </summary>
  1019. /// <typeparam name="T">数组的类型信息</typeparam>
  1020. /// <param name="arrays">任意个长度的数组</param>
  1021. /// <returns>拼接之后的最终的结果对象</returns>
  1022. /// <example>
  1023. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="SpliceByteArray" title="SpliceByteArray示例" />
  1024. /// </example>
  1025. public static T[] SpliceArray<T>(params T[][] arrays)
  1026. {
  1027. int count = 0;
  1028. for (int i = 0; i < arrays.Length; i++)
  1029. {
  1030. if (arrays[i]?.Length > 0)
  1031. {
  1032. count += arrays[i].Length;
  1033. }
  1034. }
  1035. int index = 0;
  1036. T[] buffer = new T[count];
  1037. for (int i = 0; i < arrays.Length; i++)
  1038. {
  1039. if (arrays[i]?.Length > 0)
  1040. {
  1041. arrays[i].CopyTo(buffer, index);
  1042. index += arrays[i].Length;
  1043. }
  1044. }
  1045. return buffer;
  1046. }
  1047. #endregion
  1048. #region String Array Splice
  1049. /// <summary>
  1050. /// 将一个<see cref="string"/>的数组和多个<see cref="string"/> 类型的对象整合成一个数组<br />
  1051. /// Combine an array of <see cref = "string" /> and multiple objects of type <see cref = "string" /> into an array
  1052. /// </summary>
  1053. /// <param name="first">第一个数组对象</param>
  1054. /// <param name="array">字符串数组信息</param>
  1055. /// <returns>总的数组对象</returns>
  1056. public static string[] SpliceStringArray(string first, string[] array)
  1057. {
  1058. List<string> list = new List<string>();
  1059. list.Add(first);
  1060. list.AddRange(array);
  1061. return list.ToArray();
  1062. }
  1063. /// <summary>
  1064. /// 将两个<see cref="string"/>的数组和多个<see cref="string"/> 类型的对象整合成一个数组<br />
  1065. /// Combine two arrays of <see cref="string" /> and multiple objects of type <see cref="string"/> into one array
  1066. /// </summary>
  1067. /// <param name="first">第一个数据对象</param>
  1068. /// <param name="second">第二个数据对象</param>
  1069. /// <param name="array">字符串数组信息</param>
  1070. /// <returns>总的数组对象</returns>
  1071. public static string[] SpliceStringArray(string first, string second, string[] array)
  1072. {
  1073. List<string> list = new List<string>();
  1074. list.Add(first);
  1075. list.Add(second);
  1076. list.AddRange(array);
  1077. return list.ToArray();
  1078. }
  1079. /// <summary>
  1080. /// 将两个<see cref="string"/>的数组和多个<see cref="string"/> 类型的对象整合成一个数组<br />
  1081. /// Combine two arrays of <see cref="string" /> and multiple objects of type <see cref="string"/> into one array
  1082. /// </summary>
  1083. /// <param name="first">第一个数据对象</param>
  1084. /// <param name="second">第二个数据对象</param>
  1085. /// <param name="third">第三个数据对象</param>
  1086. /// <param name="array">字符串数组信息</param>
  1087. /// <returns>总的数组对象</returns>
  1088. public static string[] SpliceStringArray(string first, string second, string third, string[] array)
  1089. {
  1090. List<string> list = new List<string>();
  1091. list.Add(first);
  1092. list.Add(second);
  1093. list.Add(third);
  1094. list.AddRange(array);
  1095. return list.ToArray();
  1096. }
  1097. #endregion
  1098. #region Url Encode Decode
  1099. // 以下代码来自于微软自身的开源库
  1100. private static int HexToInt(char h)
  1101. {
  1102. return (h >= '0' && h <= '9') ? h - '0' :
  1103. (h >= 'a' && h <= 'f') ? h - 'a' + 10 :
  1104. (h >= 'A' && h <= 'F') ? h - 'A' + 10 :
  1105. -1;
  1106. }
  1107. private static string ValidateString(string input, bool skipUtf16Validation)
  1108. {
  1109. if (skipUtf16Validation || String.IsNullOrEmpty(input))
  1110. {
  1111. return input;
  1112. }
  1113. // locate the first surrogate character
  1114. int idxOfFirstSurrogate = -1;
  1115. for (int i = 0; i < input.Length; i++)
  1116. {
  1117. if (Char.IsSurrogate(input[i]))
  1118. {
  1119. idxOfFirstSurrogate = i;
  1120. break;
  1121. }
  1122. }
  1123. // fast case: no surrogates = return input string
  1124. if (idxOfFirstSurrogate < 0)
  1125. {
  1126. return input;
  1127. }
  1128. // slow case: surrogates exist, so we need to validate them
  1129. char[] chars = input.ToCharArray();
  1130. for (int i = idxOfFirstSurrogate; i < chars.Length; i++)
  1131. {
  1132. char thisChar = chars[i];
  1133. // If this character is a low surrogate, then it was not preceded by
  1134. // a high surrogate, so we'll replace it.
  1135. if (Char.IsLowSurrogate(thisChar))
  1136. {
  1137. chars[i] = '\uFFFD';
  1138. continue;
  1139. }
  1140. if (Char.IsHighSurrogate(thisChar))
  1141. {
  1142. // If this character is a high surrogate and it is followed by a
  1143. // low surrogate, allow both to remain.
  1144. if (i + 1 < chars.Length && Char.IsLowSurrogate(chars[i + 1]))
  1145. {
  1146. i++; // skip the low surrogate also
  1147. continue;
  1148. }
  1149. // If this character is a high surrogate and it is not followed
  1150. // by a low surrogate, replace it.
  1151. chars[i] = '\uFFFD';
  1152. continue;
  1153. }
  1154. // Otherwise, this is a non-surrogate character and just move to the
  1155. // next character.
  1156. }
  1157. return new String(chars);
  1158. }
  1159. private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count)
  1160. {
  1161. if (bytes == null && count == 0)
  1162. return false;
  1163. if (bytes == null)
  1164. {
  1165. throw new ArgumentNullException("bytes");
  1166. }
  1167. if (offset < 0 || offset > bytes.Length)
  1168. {
  1169. throw new ArgumentOutOfRangeException("offset");
  1170. }
  1171. if (count < 0 || offset + count > bytes.Length)
  1172. {
  1173. throw new ArgumentOutOfRangeException("count");
  1174. }
  1175. return true;
  1176. }
  1177. private static bool IsUrlSafeChar(char ch)
  1178. {
  1179. if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
  1180. return true;
  1181. switch (ch)
  1182. {
  1183. case '-':
  1184. case '_':
  1185. case '.':
  1186. case '!':
  1187. case '*':
  1188. case '(':
  1189. case ')':
  1190. return true;
  1191. }
  1192. return false;
  1193. }
  1194. private static string UrlEncodeSpaces(string str)
  1195. {
  1196. if (str != null && str.IndexOf(' ') >= 0)
  1197. str = str.Replace(" ", "%20");
  1198. return str;
  1199. }
  1200. private static char IntToHex(int n)
  1201. {
  1202. Debug.Assert(n < 0x10);
  1203. if (n <= 9)
  1204. return (char)(n + (int)'0');
  1205. else
  1206. return (char)(n - 10 + (int)'A');
  1207. }
  1208. private static byte[] UrlEncodeToBytes(byte[] bytes)
  1209. {
  1210. int offset = 0;
  1211. int count = bytes.Length;
  1212. if (!ValidateUrlEncodingParameters(bytes, offset, count))
  1213. {
  1214. return null;
  1215. }
  1216. int cSpaces = 0;
  1217. int cUnsafe = 0;
  1218. // count them first
  1219. for (int i = 0; i < count; i++)
  1220. {
  1221. char ch = (char)bytes[offset + i];
  1222. if (ch == ' ')
  1223. cSpaces++;
  1224. else if (!IsUrlSafeChar(ch))
  1225. cUnsafe++;
  1226. }
  1227. // nothing to expand?
  1228. if (cSpaces == 0 && cUnsafe == 0)
  1229. {
  1230. // DevDiv 912606: respect "offset" and "count"
  1231. if (0 == offset && bytes.Length == count)
  1232. {
  1233. return bytes;
  1234. }
  1235. else
  1236. {
  1237. var subarray = new byte[count];
  1238. Buffer.BlockCopy(bytes, offset, subarray, 0, count);
  1239. return subarray;
  1240. }
  1241. }
  1242. // expand not 'safe' characters into %XX, spaces to +s
  1243. byte[] expandedBytes = new byte[count + cUnsafe * 2];
  1244. int pos = 0;
  1245. for (int i = 0; i < count; i++)
  1246. {
  1247. byte b = bytes[offset + i];
  1248. char ch = (char)b;
  1249. if (IsUrlSafeChar(ch))
  1250. {
  1251. expandedBytes[pos++] = b;
  1252. }
  1253. else if (ch == ' ')
  1254. {
  1255. expandedBytes[pos++] = (byte)'+';
  1256. }
  1257. else
  1258. {
  1259. expandedBytes[pos++] = (byte)'%';
  1260. expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
  1261. expandedBytes[pos++] = (byte)IntToHex(b & 0x0f);
  1262. }
  1263. }
  1264. return expandedBytes;
  1265. }
  1266. private static byte[] UrlEncode(byte[] bytes, bool alwaysCreateNewReturnValue)
  1267. {
  1268. byte[] encoded = UrlEncodeToBytes(bytes);
  1269. return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes))
  1270. ? (byte[])encoded.Clone()
  1271. : encoded;
  1272. }
  1273. /// <summary>
  1274. /// 将字符串编码为URL可以识别的字符串,中文会被编码为%开头的数据,例如 中文 转义为 %2F%E4%B8%AD%E6%96%87 <br />
  1275. /// Encoding a string as a URL-recognizable string Chinese encoded as data that begins with %, such as 中文 escaped as %2F%E4%B8%AD%E6%96%87
  1276. /// </summary>
  1277. /// <param name="str">等待转换的字符串数据</param>
  1278. /// <param name="e">编码信息,一般为 UTF8 </param>
  1279. /// <returns>编码之后的结果</returns>
  1280. public static string UrlEncode(string str, Encoding e)
  1281. {
  1282. if (str == null)
  1283. return null;
  1284. byte[] bytes = e.GetBytes(str);
  1285. return Encoding.ASCII.GetString(UrlEncode(bytes, true));
  1286. }
  1287. /// <summary>
  1288. /// 将url的编码解码为真实的字符串,例如 %2F%E4%B8%AD%E6%96%87 解码为 中文<br />
  1289. /// Decode the encoding of url as a real string, for example %2F%E4%B8%AD%E6%96%87 to 中文
  1290. /// </summary>
  1291. /// <param name="value">等待转换的值</param>
  1292. /// <param name="encoding">编码信息,一般为 UTF8</param>
  1293. /// <returns>解码之后的结果</returns>
  1294. public static string UrlDecode(string value, Encoding encoding)
  1295. {
  1296. int count = value.Length;
  1297. UrlDecoder helper = new UrlDecoder(count, encoding);
  1298. // go through the string's chars collapsing %XX and %uXXXX and
  1299. // appending each char as char, with exception of %XX constructs
  1300. // that are appended as bytes
  1301. for (int pos = 0; pos < count; pos++)
  1302. {
  1303. char ch = value[pos];
  1304. if (ch == '+')
  1305. {
  1306. ch = ' ';
  1307. }
  1308. else if (ch == '%' && pos < count - 2)
  1309. {
  1310. if (value[pos + 1] == 'u' && pos < count - 5)
  1311. {
  1312. int h1 = HexToInt(value[pos + 2]);
  1313. int h2 = HexToInt(value[pos + 3]);
  1314. int h3 = HexToInt(value[pos + 4]);
  1315. int h4 = HexToInt(value[pos + 5]);
  1316. if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
  1317. { // valid 4 hex chars
  1318. ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
  1319. pos += 5;
  1320. // only add as char
  1321. helper.AddChar(ch);
  1322. continue;
  1323. }
  1324. }
  1325. else
  1326. {
  1327. int h1 = HexToInt(value[pos + 1]);
  1328. int h2 = HexToInt(value[pos + 2]);
  1329. if (h1 >= 0 && h2 >= 0)
  1330. { // valid 2 hex chars
  1331. byte b = (byte)((h1 << 4) | h2);
  1332. pos += 2;
  1333. // don't add as char
  1334. helper.AddByte(b);
  1335. continue;
  1336. }
  1337. }
  1338. }
  1339. if ((ch & 0xFF80) == 0)
  1340. helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
  1341. else
  1342. helper.AddChar(ch);
  1343. }
  1344. return ValidateString(helper.GetString(), true);
  1345. }
  1346. #endregion
  1347. #region Deep Clone
  1348. /// <summary>
  1349. /// 使用序列化反序列化深度克隆一个对象,该对象需要支持序列化特性<br />
  1350. /// Cloning an object with serialization deserialization depth that requires support for serialization attributes
  1351. /// </summary>
  1352. /// <param name="oringinal">源对象,支持序列化</param>
  1353. /// <returns>新的一个实例化的对象</returns>
  1354. /// <exception cref="NullReferenceException"></exception>
  1355. /// <exception cref="NonSerializedAttribute"></exception>
  1356. /// <remarks>
  1357. /// <note type="warning">
  1358. /// <paramref name="oringinal"/> 参数必须实现序列化的特性
  1359. /// </note>
  1360. /// </remarks>
  1361. /// <example>
  1362. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="DeepClone" title="DeepClone示例" />
  1363. /// </example>
  1364. public static object DeepClone(object oringinal)
  1365. {
  1366. using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
  1367. {
  1368. BinaryFormatter formatter = new BinaryFormatter()
  1369. {
  1370. Context = new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Clone)
  1371. };
  1372. formatter.Serialize(stream, oringinal);
  1373. stream.Position = 0;
  1374. return formatter.Deserialize(stream);
  1375. }
  1376. }
  1377. #endregion
  1378. #region Unique String Get
  1379. /// <summary>
  1380. /// 获取一串唯一的随机字符串,长度为20,由Guid码和4位数的随机数组成,保证字符串的唯一性<br />
  1381. /// Gets a string of unique random strings with a length of 20, consisting of a GUID code and a 4-digit random number to guarantee the uniqueness of the string
  1382. /// </summary>
  1383. /// <returns>随机字符串数据</returns>
  1384. /// <example>
  1385. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\BasicFramework\SoftBasicExample.cs" region="GetUniqueStringByGuidAndRandom" title="GetUniqueStringByGuidAndRandom示例" />
  1386. /// </example>
  1387. public static string GetUniqueStringByGuidAndRandom()
  1388. {
  1389. return Guid.NewGuid().ToString("N") + new Random().Next(1000, 10000);
  1390. }
  1391. #endregion
  1392. }
  1393. class UrlDecoder
  1394. {
  1395. private int _bufferSize;
  1396. // Accumulate characters in a special array
  1397. private int _numChars;
  1398. private char[] _charBuffer;
  1399. // Accumulate bytes for decoding into characters in a special array
  1400. private int _numBytes;
  1401. private byte[] _byteBuffer;
  1402. // Encoding to convert chars to bytes
  1403. private Encoding _encoding;
  1404. private void FlushBytes()
  1405. {
  1406. if (_numBytes > 0)
  1407. {
  1408. _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
  1409. _numBytes = 0;
  1410. }
  1411. }
  1412. internal UrlDecoder(int bufferSize, Encoding encoding)
  1413. {
  1414. _bufferSize = bufferSize;
  1415. _encoding = encoding;
  1416. _charBuffer = new char[bufferSize];
  1417. // byte buffer created on demand
  1418. }
  1419. internal void AddChar(char ch)
  1420. {
  1421. if (_numBytes > 0)
  1422. FlushBytes();
  1423. _charBuffer[_numChars++] = ch;
  1424. }
  1425. internal void AddByte(byte b)
  1426. {
  1427. // if there are no pending bytes treat 7 bit bytes as characters
  1428. // this optimization is temp disable as it doesn't work for some encodings
  1429. /*
  1430. if (_numBytes == 0 && ((b & 0x80) == 0)) {
  1431. AddChar((char)b);
  1432. }
  1433. else
  1434. */
  1435. {
  1436. if (_byteBuffer == null)
  1437. _byteBuffer = new byte[_bufferSize];
  1438. _byteBuffer[_numBytes++] = b;
  1439. }
  1440. }
  1441. internal string GetString()
  1442. {
  1443. if (_numBytes > 0)
  1444. FlushBytes();
  1445. if (_numChars > 0)
  1446. return new string(_charBuffer, 0, _numChars);
  1447. else
  1448. return string.Empty;
  1449. }
  1450. }
  1451. }