时间处理
public static class DateTimeHelper { public static long GetCurrentUnixTimestamp ( ) { DateTimeOffset offset = DateTimeOffset. UtcNow; return Convert. ToInt64 ( ( offset - new DateTimeOffset ( 1970 , 1 , 1 , 0 , 0 , 0 , TimeSpan. Zero) ) . TotalSeconds) ; } public static DateTime UnixTimestampToDateTime ( long unixTimestamp) { DateTime dateTime = new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 , 0 , DateTimeKind. Utc) ; dateTime = dateTime. AddSeconds ( unixTimestamp) . ToLocalTime ( ) ; return dateTime; } public static DateTime GetCurrentDate ( ) { return DateTime. Now; } public static string FormatDateTime ( DateTime dateTime, string format = "yyyy-MM-dd HH:mm:ss" ) { return dateTime. ToString ( format) ; } public static double GetDaysDifference ( DateTime otherTime) { DateTime currentTime = DateTime. Now; TimeSpan timeSpan = currentTime. Subtract ( otherTime) ; double daysDifference = timeSpan. TotalDays; return daysDifference; } }
文件处理
public class FileHelper { public static string ReadTextFromFile ( string filePath) { if ( ! FileExists ( filePath) ) { return "" ; } return File. ReadAllText ( filePath) ; } public static List< string > ReadLineByLineWithFileReadLines ( string filePath) { return File. ReadLines ( filePath) . ToList ( ) ; } public static void WriteTextToFile ( string filePath, string text) { File. WriteAllText ( filePath, text) ; } public static void AppendTextToFile ( string filePath, string text) { File. AppendAllText ( filePath, text) ; } public static void AppendTextByLineToFile ( string filePath, string text) { File. AppendAllText ( filePath, Environment. NewLine + text) ; } public static void DeleteFile ( string filePath) { File. Delete ( filePath) ; } public static bool FileExists ( string filePath) { return File. Exists ( filePath) ; } public static bool DirectoryExists ( string path) { return Directory. Exists ( path) ; } public static void CreateDirectory ( string path) { Directory. CreateDirectory ( path) ; } }
JSON处理
public static class JsonHelper { public static string SerializeObject ( object obj) { return JsonConvert. SerializeObject ( obj) ; } public static T DeserializeObject < T> ( string json) { return JsonConvert. DeserializeObject < T> ( json) ; } public static string SerializeObjectIndented ( object obj) { return JsonConvert. SerializeObject ( obj, Formatting. Indented) ; } public static void SerializeObjectToFile ( object obj, string filePath) { File. WriteAllText ( filePath, SerializeObject ( obj) ) ; } public static T DeserializeObjectFromFile < T> ( string filePath) { string json = File. ReadAllText ( filePath) ; return DeserializeObject < T> ( json) ; } }
字符串处理
public static class StringHelper { public static string ToUpperCase ( string input) { return input. ToUpper ( ) ; } public static string ToLowerCase ( string input) { return input. ToLower ( ) ; } public static string TrimString ( string input) { return input. Trim ( ) ; } public static string FormatString ( string format, params object [ ] args) { return string . Format ( format, args) ; } public static byte [ ] StringToByteArray ( string input) { return Encoding. UTF8. GetBytes ( input) ; } public static string ByteArrayToString ( byte [ ] bytes) { return Encoding. UTF8. GetString ( bytes) ; } public static string GetMD5Hash ( string input) { using ( MD5 md5Hash = MD5. Create ( ) ) { byte [ ] data = md5Hash. ComputeHash ( Encoding. UTF8. GetBytes ( input) ) ; StringBuilder sBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < data. Length; i++ ) { sBuilder. Append ( data[ i] . ToString ( "x2" ) ) ; } return sBuilder. ToString ( ) ; } } public static bool IsMD5HashMatch ( string input, string storedHash) { string computedHash = GetMD5Hash ( input) ; return computedHash. Equals ( storedHash, StringComparison. OrdinalIgnoreCase) ; } public static bool IsValidString ( string input) { if ( input == null || input. Length <= 7 ) { return false ; } bool hasUpper = input. Any ( char . IsUpper) ; bool hasLower = input. Any ( char . IsLower) ; bool hasDigit = input. Any ( char . IsDigit) ; return hasUpper && hasLower && hasDigit; } public static bool IsValidUrl ( string url) { if ( string . IsNullOrWhiteSpace ( url) ) { return false ; } Regex UrlRegex = new Regex ( @"^http://(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$" , RegexOptions. IgnoreCase) ; return UrlRegex. IsMatch ( url) ; } private static readonly Regex UrlRegex = new Regex ( @"^(http(?:s)?://)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::\d+)?(/[\w ./-]*)?$" ) ; public static bool IsPossibleUrlWithIpAndPort ( string url) { return UrlRegex. IsMatch ( url) ; } private static readonly Regex Ipv4Regex = new Regex ( @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" ) ; public static bool IsValidIPv4 ( string ip) { return Ipv4Regex. IsMatch ( ip) ; } }
简易日志处理
public enum LogLevel { Log, Debug, Info, Warn, Error} public class SimpleLogger { private static string _baseLogPath; private static string _currentDateFolder; private static string logs = "Logs" ; private static string GetTodayDateString ( ) { return DateTime. Now. ToString ( "yyyyMMdd" ) ; } private static void CreateLogFolderIfNotExists ( ) { string fullPath = System. IO. Path. Combine ( _baseLogPath, _currentDateFolder) ; if ( ! System. IO. Directory. Exists ( fullPath) ) { System. IO. Directory. CreateDirectory ( fullPath) ; } } public static void WriteLog ( LogLevel logLevel, string message) { string debugPath = AppDomain. CurrentDomain. BaseDirectory; string logPath = System. IO. Path. Combine ( debugPath, logs) ; _baseLogPath = logPath; _currentDateFolder = GetTodayDateString ( ) ; CreateLogFolderIfNotExists ( ) ; string logFileName = $" { logLevel. ToString ( ) . ToLower ( ) } _ { _currentDateFolder } .log" ; string fullPath = System. IO. Path. Combine ( _baseLogPath, _currentDateFolder, logFileName) ; using ( System. IO. StreamWriter sw = System. IO. File. AppendText ( fullPath) ) { sw. WriteLine ( $" { DateTime. Now } : [ { logLevel. ToString ( ) } ] { message } " ) ; } } }