Files
GX.O3.WMS/APP.O3/Shared/Extensions/StringExtensions.cs
T

406 lines
13 KiB
C#
Executable File

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Opsoft.NetCore.O3App.Shared
{
public static class StringExtensions
{
public static int ToInt32(this string source, int @default = 0)
{
if (!Int32.TryParse(source, out int value))
{
value = @default;
}
return value;
}
public static long ToInt64(this string source, long @default = 0)
{
if (!Int64.TryParse(source, out long value))
{
value = @default;
}
return value;
}
public static decimal ToDecimal(this string source, decimal @default = 0m)
{
if (!decimal.TryParse(source, out decimal value))
{
value = @default;
}
return value;
}
public static TOut ToEnum<TOut>(this string source)
{
Guard.ArgumentNotNullOrWhiteSpace(source, nameof(source));
var outputType = typeof(TOut);
if (outputType.IsEnum)
{
if (outputType.IsEnumDefined(source))
{
var obj = Enum.Parse(outputType, source);
if (obj != null)
{
return (TOut)obj;
}
}
}
return default(TOut);
}
public static DateTime ToDateTime(this string source)
{
var result = DateTime.Now;
DateTime.TryParse(source, out result);
return result;
}
public static string Format4CSV(this IEnumerable<string> array)
{
if (array == null)
{
return string.Empty;
}
List<string> fields = new List<string>();
array.ToList().ForEach(field => fields.Add(field.Format4CSV()));
return string.Join(",", fields);
}
public static string Format4CSV(this string source)
{
if (source.IsNullOrEmpty())
{
return string.Empty;
}
string rtn = source;
rtn = System.Text.RegularExpressions.Regex.Replace(rtn, "\"", "\"\"");
rtn = "\"" + rtn + "\"";
return rtn;
}
public static bool IsNullOrEmpty(this string source)
{
return string.IsNullOrEmpty(source);
}
public static bool NotNullOrEmpty(this string source)
{
return !string.IsNullOrEmpty(source);
}
public static string Null2Empty(this object source)
{
return source == null || Convert.IsDBNull(source) ? string.Empty : source.ToString();
}
public static bool IsNullOrWhiteSpace(this string source)
{
return string.IsNullOrWhiteSpace(source);
}
public static bool NotNullOrWhiteSpace(this string source)
{
return !string.IsNullOrWhiteSpace(source);
}
public static void Dump(this string source, string path)
{
Guard.ArgumentNotNullOrWhiteSpace(nameof(source), source);
Guard.ArgumentNotNullOrWhiteSpace(nameof(path), path);
using (System.IO.StreamWriter writer = System.IO.File.CreateText(path))
{
writer.Write(source);
writer.Flush();
writer.Close();
}
}
public static void Dump2CSV(this StringBuilder source, string path)
{
Guard.ArgumentNotNull(source, nameof(source));
source.ToString().Dump2CSV(path);
}
public static void Dump2CSV(this string source, string path)
{
Guard.ArgumentNotNullOrWhiteSpace(source, nameof(source));
Guard.ArgumentNotNullOrWhiteSpace(path, nameof(path));
FileInfo file = new FileInfo(path);
if (!file.Directory.Exists)
throw new DirectoryNotFoundException(path);
var bytes = Encoding.UTF8.GetBytes(source);
var byteArray = new byte[bytes.Length + 3];
var preBytes = new byte[] { 0xEF, 0xBB, 0xBF };
Array.Copy(preBytes, 0, byteArray, 0, 3);
Array.Copy(bytes, 0, byteArray, 3, bytes.Length);
using (FileStream dumpFile = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
dumpFile.Write(byteArray, 0, byteArray.Length);
dumpFile.Flush();
dumpFile.Close();
}
}
public static string Left(this string source, int length = 0, string suffix = "")
{
if (source.IsNullOrEmpty())
{
return string.Empty;
}
if (length > 0 && source.Length > length)
{
return source.Substring(0, length) + suffix;
}
else
{
return source;
}
}
public static string Right(this string source, int length = 0, string prefix = "")
{
if (source.IsNullOrEmpty())
{
return string.Empty;
}
if (length > 0 && source.Length > length)
{
return string.Join("", source.Skip(source.Length - length));
}
else
{
return source;
}
}
/// <summary>
/// 将字符串缩短到指定的长度,中间使用指定的内容替换掉。比如:1234567890 --> 12...90
/// </summary>
/// <param name="source"></param>
/// <param name="maxLength"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string Shorten(this string source, int maxLength, string replacement = "...")
{
if (string.IsNullOrWhiteSpace(source)) return string.Empty;
int sourceLength = source.Length;
if (maxLength <= 0 || sourceLength <= maxLength) return source;
int replacementLength = replacement.Length;
if (maxLength < replacementLength || replacementLength <= 0) return source.Left(maxLength);
int shortenLength = sourceLength - maxLength;
if (shortenLength < replacementLength)
{
replacement = replacement.Substring(0, shortenLength);
replacementLength = replacement.Length;
}
int summaryLength = maxLength - replacementLength;
if (summaryLength == 1)
return string.Concat(source[0].ToString(), replacement);
int leftSummary = summaryLength / 2;
int rightSummary = summaryLength - leftSummary;
return string.Concat(source.Left(leftSummary), replacement, source.Right(rightSummary));
}
/// <summary>
/// 给字符串做掩码。比如:"13012345678".Mask() --> "130****5678"
/// </summary>
public static string Mask(this string source, char replacement = '*', int left = 3, int right = 4)
{
if (string.IsNullOrWhiteSpace(source)) return string.Empty;
int maskLength = source.Length - left - right;
if (maskLength <= 0) return source;
return $"{source.Substring(0, left)}{new string(replacement, maskLength)}{source.Substring(source.Length - right)}";
}
public static string NullOrEmpty2Default(this string source, string defaultString = "")
{
string input = source;
if (string.IsNullOrWhiteSpace(input))
return defaultString;
return input;
}
public static string ToJson(this object value)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(value);
}
public static string ToJson(this object value, Newtonsoft.Json.Formatting formatting)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(value, formatting);
}
public static string ToJson(this object value, Newtonsoft.Json.JsonSerializerSettings settings)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(value, settings);
}
public static T FromJson<T>(this string value)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
}
public static T FromJson<T>(this string value, Newtonsoft.Json.JsonSerializerSettings settings)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value, settings);
}
public static T FromXml<T>(this string xmlSource)
{
if (string.IsNullOrWhiteSpace(xmlSource))
{
return default(T);
}
using (var reader = new StringReader(xmlSource))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}
}
public static T FromXml<T>(this Stream stream)
{
if (stream == null)
{
return default(T);
}
using (stream)
{
XmlSerializer serial = new XmlSerializer(typeof(T));
return (T)serial.Deserialize(stream);
}
}
public static string ToXml<T>(this T value)
where T : class, new()
{
if (value == null)
{
return string.Empty;
}
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
public static string ToBase64(this string source, Encoding encoding)
{
if (string.IsNullOrWhiteSpace(source))
{
return string.Empty;
}
if (encoding == null)
{
encoding = Encoding.UTF8;
}
return Convert.ToBase64String(encoding.GetBytes(source));
}
public static string FromBase64(this string source, Encoding encoding)
{
if (string.IsNullOrWhiteSpace(source))
{
return string.Empty;
}
if (encoding == null)
{
encoding = Encoding.UTF8;
}
return encoding.GetString(Convert.FromBase64String(source));
}
/// <summary>
/// 压缩字符串
/// </summary>
/// <param name="source">未压缩的字符串</param>
/// <returns>压缩的字符串</returns>
public static string GZipCompress(this string source)
{
Guard.ArgumentNotNullOrWhiteSpace(source, nameof(source));
byte[] sourceData = Encoding.Unicode.GetBytes(source);
MemoryStream stream = new MemoryStream();
Stream gzip = new GZipStream(stream, CompressionMode.Compress);
gzip.Write(sourceData, 0, sourceData.Length);
gzip.Close();
byte[] compressedData = stream.ToArray();
return Convert.ToBase64String(compressedData, 0, compressedData.Length);
}
/// <summary>
/// 解压缩字符串
/// </summary>
/// <param name="compressedSource">压缩的字符串</param>
/// <returns>未压缩的字符串</returns>
public static string GZipDecompress(this string compressedSource)
{
Guard.ArgumentNotNullOrWhiteSpace(compressedSource, nameof(compressedSource));
byte[] buffer = Convert.FromBase64String(compressedSource);
var zipStream = new GZipStream(new MemoryStream(buffer), CompressionMode.Decompress);
StringBuilder unCompressed = new StringBuilder();
byte[] block = new byte[4096];
while (true)
{
int bytesRead = zipStream.Read(block, 0, block.Length);
if (bytesRead <= 0)
{
break;
}
else
{
unCompressed.Append(Encoding.Unicode.GetString(block, 0, bytesRead));
}
}
zipStream.Close();
return unCompressed.ToString();
}
public static string GetMD5Hash(this string source)
{
if (source.IsNullOrWhiteSpace())
{
return string.Empty;
}
var md5Hasher = System.Security.Cryptography.MD5.Create();
byte[] hash = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(source));
return string.Join(string.Empty, hash.Select(_ => _.ToString("x2")));
}
public static List<int> SlitToIntList(this string source, char splitChar)
{
if (string.IsNullOrWhiteSpace(source))
{
return new List<int>();
}
return source.Split(new[] { splitChar }).Select(str =>
{
return int.TryParse(str, out int result) ? result : 0;
}).ToList();
}
}
}