c# 工具类(字符串和时间,文件)
- using System;
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Windows.Browser;
- namespace SL_COMMON
- {
- public class Utils
- {
- #region String字符串类
- /**/
- /// <summary>
- /// 过滤字符
- /// </summary>
- public static string Replace(string strOriginal, string oldchar, string newchar)
- {
- if (string.IsNullOrEmpty(strOriginal))
- return "";
- string tempChar = strOriginal;
- tempChar = tempChar.Replace(oldchar, newchar);
- return tempChar;
- }
- /**/
- /// <summary>
- /// 过滤非法字符
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string ReplaceBadChar(string str)
- {
- if (string.IsNullOrEmpty(str))
- return "";
- string strBadChar, tempChar;
- string[] arrBadChar;
- strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\",";
- arrBadChar = SplitString(strBadChar, ",");
- tempChar = str;
- for (int i = 0; i < arrBadChar.Length; i++)
- {
- if (arrBadChar[i].Length > 0)
- tempChar = tempChar.Replace(arrBadChar[i], "");
- }
- return tempChar;
- }
- /**/
- /// <summary>
- /// 检查是否含有非法字符
- /// </summary>
- /// <param name="str">要检查的字符串</param>
- /// <returns></returns>
- public static bool ChkBadChar(string str)
- {
- bool result = false;
- if (string.IsNullOrEmpty(str))
- return result;
- string strBadChar, tempChar;
- string[] arrBadChar;
- strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\"";
- arrBadChar = SplitString(strBadChar, ",");
- tempChar = str;
- for (int i = 0; i < arrBadChar.Length; i++)
- {
- if (tempChar.IndexOf(arrBadChar[i]) >= 0)
- result = true;
- }
- return result;
- }
- /**/
- /// <summary>
- /// 分割字符串
- /// </summary>
- public static string[] SplitString(string strContent, string strSplit)
- {
- if (string.IsNullOrEmpty(strContent))
- {
- return null;
- }
- int i = strContent.IndexOf(strSplit);
- if (strContent.IndexOf(strSplit) < 0)
- {
- string[] tmp = { strContent };
- return tmp;
- }
- //return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
- return Regex.Split(strContent, @strSplit.Replace(".", @"\."));
- }
- /**/
- /// <summary>
- /// string型转换为int型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <returns>转换后的int类型结果.如果要转换的字符串是非数字,则返回-1.</returns>
- public static int StrToInt(object strValue)
- {
- int defValue = -1;
- if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10))
- {
- return defValue;
- }
- string val = strValue.ToString();
- string firstletter = val[0].ToString();
- if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1)
- {
- return defValue;
- }
- else if (val.Length == 10 && !IsNumber(firstletter))
- {
- return defValue;
- }
- int intValue = defValue;
- if (strValue != null)
- {
- bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString());
- if (IsInt)
- {
- intValue = Convert.ToInt32(strValue);
- }
- }
- return intValue;
- }
- /**/
- /// <summary>
- /// string型转换为int型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int StrToInt(object strValue, int defValue)
- {
- if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10))
- {
- return defValue;
- }
- string val = strValue.ToString();
- string firstletter = val[0].ToString();
- if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1)
- {
- return defValue;
- }
- else if (val.Length == 10 && !IsNumber(firstletter))
- {
- return defValue;
- }
- int intValue = defValue;
- if (strValue != null)
- {
- bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString());
- if (IsInt)
- {
- intValue = Convert.ToInt32(strValue);
- }
- }
- return intValue;
- }
- /**/
- /// <summary>
- /// string型转换为时间型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的时间类型结果</returns>
- public static DateTime StrToDateTime(object strValue, DateTime defValue)
- {
- if ((strValue == null) || (strValue.ToString().Length > 20))
- {
- return defValue;
- }
- DateTime intValue;
- if (!DateTime.TryParse(strValue.ToString(), out intValue))
- {
- intValue = defValue;
- }
- return intValue;
- }
- /**/
- /// <summary>
- /// 判断给定的字符串(strNumber)是否是数值型
- /// </summary>
- /// <param name="strNumber">要确认的字符串</param>
- /// <returns>是则返加true 不是则返回 false</returns>
- public static bool IsNumber(string strNumber)
- {
- return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
- }
- /**/
- /// <summary>
- /// 检测是否符合email格式
- /// </summary>
- /// <param name="strEmail">要判断的email字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsValidEmail(string strEmail)
- {
- return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((
[0−9]1,3\.[0−9]1,3\.[0−9]1,3\.)|(([\w−]+\.)+))([a−zA−Z]2,4|[0−9]1,3)(
?)$");
- }
- /**/
- /// <summary>
- /// 检测是否符合url格式,前面必需含有http://
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static bool IsURL(string url)
- {
- return Regex.IsMatch(url, @"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$");
- }
- /**/
- /// <summary>
- /// 检测是否符合电话格式
- /// </summary>
- /// <param name="phoneNumber"></param>
- /// <returns></returns>
- public static bool IsPhoneNumber(string phoneNumber)
- {
- |\d{3}-)?\d{7,8}$");
- }
- /**/
- /// <summary>
- /// 检测是否符合身份证号码格式
- /// </summary>
- /// <param name="num"></param>
- /// <returns></returns>
- public static bool IsIdentityNumber(string num)
- {
- return Regex.IsMatch(num, @"^\d{17}[\d|X]|\d{15}$");
- }
- #endregion
- #region Sql类
- /**/
- /// <summary>
- /// 检测是否有Sql危险字符
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeSqlString(string str)
- {
- return !Regex.IsMatch(str, @"[-|;|,|\/|||
|
|\}|\{|%|@|\*|!|\']");
- }
- /**/
- /// <summary>
- /// 替换sql语句中的单引号
- /// </summary>
- public static string ReplaceBadSQL(string str)
- {
- string str2;
- if (str == null)
- {
- str2 = "";
- }
- else
- {
- str = str.Replace("'", "''");
- str2 = str;
- }
- return str2;
- }
- #endregion
- #region Html类
- /**/
- /// <summary>
- /// 返回 HTML 字符串的解码结果
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>解码结果</returns>
- public static string HtmlDecode(string str)
- {
- //str = str.Replace("''", "'");
- return HttpUtility.HtmlDecode(str);
- }
- /**/
- /// <summary>
- /// 替换html字符
- /// </summary>
- public static string EncodeHtml(string strHtml)
- {
- if (strHtml != "")
- {
- strHtml = strHtml.Replace(",", "&def");
- strHtml = strHtml.Replace("'", "&dot");
- strHtml = strHtml.Replace(";", "&dec");
- return strHtml;
- }
- return "";
- }
- /**/
- /// <summary>
- /// 替换回车换行符为html换行符
- /// </summary>
- public static string StrFormat(string str)
- {
- string str2;
- if (str == null)
- {
- str2 = "";
- }
- else
- {
- str = str.Replace("\r\n", "<br />");
- str = str.Replace("\n", "<br />");
- str2 = str;
- }
- return str2;
- }
- #endregion
- #region DateTime类
- /**/
- /// <summary>
- /// 返回当前服务器时间的 yyyy-MM-dd 日期格式string
- /// </summary>
- public static string GetDate()
- {
- return DateTime.Now.ToString("yyyy-MM-dd");
- }
- /**/
- /// <summary>
- ///返回当前服务器时间的标准时间格式string HH:mm:ss
- /// </summary>
- public static string GetTime()
- {
- return DateTime.Now.ToString("HH:mm:ss");
- }
- /**/
- /// <summary>
- /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss
- /// </summary>
- public static string GetDateTime()
- {
- return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- }
- /**/
- /// <summary>
- /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss:fffffff
- /// </summary>
- public static string GetDateTimeF()
- {
- return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
- }
- /**/
- /// <summary>
- /// 将string类型的fDateTime转换为formatStr格式的日期类型
- /// </summary>
- public static string GetStandardDateTime(string fDateTime, string formatStr)
- {
- DateTime s = Convert.ToDateTime(fDateTime);
- return s.ToString(formatStr);
- }
- /**/
- /// <summary>
- ///将string类型的fDateTime转换为日期类型 yyyy-MM-dd HH:mm:ss
- /// </sumary>
- public static string GetStandardDateTime(string fDateTime)
- {
- return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
- }
- /**/
- /// <summary>
- /// 返回相差的秒数
- /// </summary>
- /// <param name="Time"></param>
- /// <param name="Sec"></param>
- /// <returns></returns>
- public static int StrDateDiffSeconds(string Time, int Sec)
- {
- TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
- if (ts.TotalSeconds > int.MaxValue)
- {
- return int.MaxValue;
- }
- else if (ts.TotalSeconds < int.MinValue)
- {
- return int.MinValue;
- }
- return (int)ts.TotalSeconds;
- }
- /**/
- /// <summary>
- /// 返回相差的分钟数
- /// </summary>
- /// <param name="time"></param>
- /// <param name="minutes"></param>
- /// <returns></returns>
- public static int StrDateDiffMinutes(string time, int minutes)
- {
- if (time == "" || time == null)
- return 1;
- TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
- if (ts.TotalMinutes > int.MaxValue)
- {
- return int.MaxValue;
- }
- else if (ts.TotalMinutes < int.MinValue)
- {
- return int.MinValue;
- }
- return (int)ts.TotalMinutes;
- }
- /**/
- /// <summary>
- /// 返回相差的小时数
- /// </summary>
- /// <param name="time"></param>
- /// <param name="hours"></param>
- /// <returns></returns>
- public static int StrDateDiffHours(string time, int hours)
- {
- if (time == "" || time == null)
- return 1;
- TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
- if (ts.TotalHours > int.MaxValue)
- {
- return int.MaxValue;
- }
- else if (ts.TotalHours < int.MinValue)
- {
- return int.MinValue;
- }
- return (int)ts.TotalHours;
- }
- #endregion
- #region file类
- /**/
- /// <summary>
- /// 文件是否存在
- /// </summary>
- /// <param name="filePath">相对路径</param>
- /// <returns></returns>
- public static bool FileExists(string filePath)
- {
- if (string.IsNullOrEmpty(filePath))
- return false;
- filePath = HttpContext.Current.Server.MapPath(filePath);
- DirectoryInfo dirInfo = new DirectoryInfo(filePath);
- if (dirInfo.Exists)
- return true;
- return false;
- }
- #endregion
- }
- }
c# 工具类(字符串和时间,文件)的更多相关文章
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- ZIP解压缩文件的工具类【支持多级文件夹|全】
ZIP解压缩文件的工具类[支持多级文件夹|全] 作者:Vashon 网上有非常多的加压缩演示样例代码.可是都仅仅是支持一级文件夹的操作.假设存在多级文件夹的话就不行了. 本解压缩工具类经过多次检查及重 ...
- 【Hutool】Hutool工具类之日期时间工具——DateUtil
一.用于取代Date对象的DateTime对象 再也不用Date SimpleDateFormat Calendar之间倒腾来倒腾去了!日期创建-获取-操作一步到位! 如果JDK版本更新到了8及以上, ...
- 【Hutool】工具类之日期时间工具-DateUtil
日期时间工具类 一.依赖 <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-al ...
- [工具类] 读取解析json文件
读取json文件并转换为字符串 /** * 通过本地文件访问json并读取 * * @param path:json文件路径 * @return:json文件的内容 */ public static ...
- (工具类)MD5算法|时间格式转换|字符串转数字
package vote.utils; import java.security.MessageDigest; import java.text.SimpleDateFormat; import ja ...
- 工具类。父类(Pom文件)
ego_parent(pom文件) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- PHP 图片上传工具类(支持多文件上传)
====================ImageUploadTool======================== <?php class ImageUploadTool { private ...
- 利用commons-io.jar包中FileUtils和IOUtils工具类操作流及文件
1.String IOUtils.toString(InputStream input),传入输入流对象,返回字符串,有多重重载,可按需要传参 用例: @Test public void showIn ...
- java调用svnkit工具类上传本地文件到svn服务器
package org.jenkinsci.plugins.svn.upload.step; import java.io.*; import org.tmatesoft.svn.core.SVNCo ...
随机推荐
- 原生js获取left值和top值
在用js做动态效果时,通常需要获取元素绝对定位中的left和top属性值.比如做一个碰撞广告,就要不停的获取元素的top和left属性值. 需要注意的事:取值的元素必须要设置position:abso ...
- CDN和CDN加速原理
随着互联网的发展,用户在使用网络时对网站的浏览速度和效果愈加重视,但由于网民数量激增,网络访问路径过长,从 而使用户的访问质量受到严重影响.特别是当用户与网站之间的链路被突发的大流量数据拥塞时,对于异 ...
- Win10_x86_x64PE维护光盘——我用过最好用的PE
先感谢hongxj和fish2006两位大大提供的PE. 先放出所有工具的下载地址: hongxj的PE:https://yunpan.cn/crAw6HS6ar9ck 访问密码 4a4e fish ...
- css 如何隐藏滚动条
原理: 把滚动条设为完全透明: /* 设置滚动条的样式 */::-webkit-scrollbar { width: 12px;} /* 滚动槽 */::-webkit-scrollbar-track ...
- EntityFramework Core 运行dotnet ef命令迁移背后本质是什么?(EF Core迁移原理)
前言 终于踏出第一步探索EF Core原理和本质,过程虽然比较漫长且枯燥乏味还得反复论证,其中滋味自知,EF Core的强大想必不用我再过多废话,有时候我们是否思考过背后到底做了些什么,到底怎么实现的 ...
- Maven-08: 插件的配置
完成了插件和生命周期的绑定之后,用户还可以配置插件目标的参数,进一步调整插件目标所执行的任务,以满足项目的需求.几乎所有Maven插件的目标都有一些可配置的参数.用户可以通过命令行和POM配置等方式来 ...
- MySQL数据库学习一 数据库概述
1.1 数据库管理技术的发展阶段 人工管理阶段,文件系统阶段,数据库系统阶段. 1.2 数据库系统阶段涉及的概念 数据库(Database DB):是指长期保存在计算机的存储设备上,按照一定的规则组织 ...
- iOS学习——tableview中带编辑功能的cell键盘弹出遮挡和收起问题解决
最近在项目中经常用到UITableView中的cell中带有UITextField或UITextView的情况,然后在这种场景下,当我们点击屏幕较下方的cell进行编辑时,这时候键盘弹出来会出现遮挡待 ...
- Vmware虚拟机不能使用键盘的解决方法
有个笔记本thinkpad T440要重装系统,但又怕前面的资料丢失,因此打算直接将整个物理机迁移到VCenter 6.5上去,比GHOST什么的方便多了,利用Vmware Convert工具直接在线 ...
- 【Python】 SQLAlchemy的初步使用
SQLAlchemy 在很多Python的web框架中都整合进了SQLAlchemy这个主要发挥ORM作用的模块.所谓ORM,就是把复杂的SQL语句给包装成更加面向对象,易于理解的样子.在操作数据库的 ...