.NET常用操作小知识
一、.NET截取指定长度汉字超出部分以“.....”表示
/// <summary>
/// 将指定字符串按指定长度进行剪切,
/// </summary>
/// <param name= "oldStr "> 需要截断的字符串 </param>
/// <param name= "maxLength "> 字符串的最大长度 </param>
/// <param name= "endWith "> 超过长度的后缀 </param>
/// <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns>
public static string StringTruncat(string oldStr, int maxLength, string endWith)
{
if (string.IsNullOrEmpty(oldStr))
// throw new NullReferenceException( "原字符串不能为空 ");
return oldStr + endWith;
if (maxLength < )
throw new Exception("返回的字符串长度必须大于[0] ");
if (oldStr.Length > maxLength)
{
string strTmp = oldStr.Substring(, maxLength);
if (string.IsNullOrEmpty(endWith))
return strTmp;
else
return strTmp + endWith;
}
return oldStr;
}
调用:
var v = StringTruncat("广东省深圳市西乡镇宝安区", 10, "...");
显示:广东省深圳市西乡镇宝...
二、过滤SQL非法字符串
/// <summary>
/// 过滤SQL非法字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Filter(string value)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
value = Regex.Replace(value, @";", string.Empty);
value = Regex.Replace(value, @"'", string.Empty);
value = Regex.Replace(value, @"&", string.Empty);
value = Regex.Replace(value, @"%20", string.Empty);
value = Regex.Replace(value, @"--", string.Empty);
value = Regex.Replace(value, @"==", string.Empty);
value = Regex.Replace(value, @"<", string.Empty);
value = Regex.Replace(value, @">", string.Empty);
value = Regex.Replace(value, @"%", string.Empty);
return value;
}
三、穿过代理服务器取远程用户真实IP地址:
if(Request.ServerVariables["HTTP_VIA"]!=null)
{
string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
}
四、sql server中 len和datalength区别
select len('a好') //返回为2
select datalength('a好') //返回为3
五、截取指定字节长度的字符串扩展方法
public static class Extension
{
/// <summary>
/// 截取指定字节长度的字符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="len">截取字节长度</param>
/// <returns></returns>
public static string CutByteString(this string str, int len)
{
string result = string.Empty;// 最终返回的结果
if (string.IsNullOrEmpty(str)) { return result; }
int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
int charLen = str.Length;// 把字符平等对待时的字符串长度
int byteCount = ;// 记录读取进度
int pos = ;// 记录截取位置
if (byteLen > len)
{
for (int i = ; i < charLen; i++)
{
if (Convert.ToInt32(str.ToCharArray()[i]) > )// 按中文字符计算加2
{ byteCount += ; }
else// 按英文字符计算加1
{ byteCount += ; }
if (byteCount > len)// 超出时只记下上一个有效位置
{
pos = i;
break;
}
else if (byteCount == len)// 记下当前位置
{
pos = i + ;
break;
}
}
if (pos >= )
{ result = str.Substring(, pos); }
}
else
{ result = str; }
return result;
} /// <summary>
/// 截取指定字节长度的字符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="startIndex">起始位置</param>
/// <param name="len">截取字节长度</param>
/// <returns></returns>
public static string CutByteString(this string str, int startIndex, int len)
{
string result = string.Empty;// 最终返回的结果
if (string.IsNullOrEmpty(str)) { return result; } int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
int charLen = str.Length;// 把字符平等对待时的字符串长度 if (startIndex == )
{ return CutByteString(str, len); }
else if (startIndex >= byteLen)
{ return result; }
else //startIndex < byteLen
{
int AllLen = startIndex + len;
int byteCountStart = ;// 记录读取进度
int byteCountEnd = ;// 记录读取进度
int startpos = ;// 记录截取位置
int endpos = ;// 记录截取位置
for (int i = ; i < charLen; i++)
{
if (Convert.ToInt32(str.ToCharArray()[i]) > )// 按中文字符计算加2
{ byteCountStart += ; }
else// 按英文字符计算加1
{ byteCountStart += ; }
if (byteCountStart > startIndex)// 超出时只记下上一个有效位置
{
startpos = i;
AllLen = startIndex + len - ;
break;
}
else if (byteCountStart == startIndex)// 记下当前位置
{
startpos = i + ;
break;
}
} if (startIndex + len <= byteLen)//截取字符在总长以内
{
for (int i = ; i < charLen; i++)
{
if (Convert.ToInt32(str.ToCharArray()[i]) > )// 按中文字符计算加2
{ byteCountEnd += ; }
else// 按英文字符计算加1
{ byteCountEnd += ; }
if (byteCountEnd > AllLen)// 超出时只记下上一个有效位置
{
endpos = i;
break;
}
else if (byteCountEnd == AllLen)// 记下当前位置
{
endpos = i + ;
break;
}
}
endpos = endpos - startpos;
}
else if (startIndex + len > byteLen)//截取字符超出总长
{
endpos = charLen - startpos;
}
if (endpos >= )
{ result = str.Substring(startpos, endpos); }
}
return result;
}
}
调用:
//=》特殊处理 只读取20位长度的User数据
if (System.Text.Encoding.Default.GetBytes(user).Length > )//Saitor
{
user = user.CutByteString();
}
六、使用记秒表检查程序运行时间
如果你担忧某些代码非常耗费时间,可以用StopWatch来检查这段代码消耗的时间,如下面的代码所示 System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal total = ;
int limit = ;
for (int i = ; i < limit; ++i)
{
total = total + (Decimal)Math.Sqrt(i);
}
timer.Stop();
Console.WriteLine(“Sum of sqrts: {}”,total);
Console.WriteLine(“Elapsed milliseconds: {}”,
timer.ElapsedMilliseconds);
Console.WriteLine(“Elapsed time: {}”, timer.Elapsed); 现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。 以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。 class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
{
public AutoStopwatch()
{
Start(); //base.Start();
}
public void Dispose()
{
Stop();//base.Stop();
Console.WriteLine(“Elapsed: {}”, this.Elapsed);
}
}
借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。 using (new AutoStopwatch())
{
Decimal total2 = ;
int limit2 = ;
for (int i = ; i < limit2; ++i)
{
total2 = total2 + (Decimal)Math.Sqrt(i);
}
}
七、使用等待光标
当程序正在后台运行保存或是册除操作时,应当将光标状态修改为忙碌。可使用下面的技巧。 class AutoWaitCursor : IDisposable
{
private Control _target;
private Cursor _prevCursor = Cursors.Default;
public AutoWaitCursor(Control control)
{
if (control == null)
{
throw new ArgumentNullException(“control”);
}
_target = control;
_prevCursor = _target.Cursor;
_target.Cursor = Cursors.WaitCursor;
}
public void Dispose()
{
_target.Cursor = _prevCursor;
}
} 用法如下所示,这个写法,是为了预料到程序可能会抛出异常 using (new AutoWaitCursor(this))
{
...
throw new Exception();
}
如代码所示,即使抛出异常,光标也可以恢复到之间的状态。
.NET常用操作小知识的更多相关文章
- javascript常用的小知识
1. oncontextmenu="window.event.returnvalue=false" 将彻底屏蔽鼠标右键 <table border oncontextmenu ...
- 编程小白入门分享二:IntelliJ IDEA的入门操作小知识
idea简介 IDEA 全称 IntelliJ IDEA,是java编程语言开发的集成环境.IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示.重构.J2EE支 ...
- 常用JS小知识汇总
1 上传图片:html代码 <input id="image" type='file' name='myFile' size='15' onchange="show ...
- Kivy之常用的小知识
1.设置标题 app.title = '测试' 2.设置屏幕长度 Window.size=1000,600 3.设置屏幕右上角icon app.title = r'C:\Users\Administr ...
- MySQL不常用、易忽略的小知识
笔者从事开发也有一段时间了,关于数据库方面的一些小知识在这里总结一下 1.count(*),count(1)与count(column)区别 count(*)对行的数目进行计算,包含NULL coun ...
- s性能优化方面的小知识
总结的js性能优化方面的小知识 前言 一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够 ...
- ArcGIS中的坐标系:基本概念和常用操作(一)
本文呢是主要是借鉴李郎平李大大的博士论文和百度百科,里面还有一点点我自己的理解,希望能帮助自己加深对于坐标系的认识. 李大大的博客:http://blog.sciencenet.cn/u/Brume ...
- 常用 JavaScript 小技巧及原理详解
善于利用JS中的小知识的利用,可以很简洁的编写代码 1. 使用!!模拟Boolean()函数 原理:逻辑非操作一个数据对象时,会先将数据对象转换为布尔值,然后取反,两个!!重复取反,就实现了转换为布尔 ...
- DevExpress之GridControl控件小知识
DevExpress之GridControl控件小知识 一.当代码中的DataTable中有建数据关系时,DevExpress 的 GridControl 会自动增加一个子视图 .列名也就是子表的字段 ...
随机推荐
- 负载均衡server load balancer
负载均衡(Server Load Balancer,简称SLB)是对多台云服务器进行流量分发的负载均衡服务.SLB可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性. ( ...
- 【一】 sched.h
第一个数据结构体是 task_struct ,这个数据结构被内核用来表示进程,包含其所有信息. 定义于文件 include/linux/sched.h 中,先看看其完整定义 struct task_s ...
- C++ RAII手法实例,不使用智能指针
/* * ===================================================================================== * * Filen ...
- Java数据库增删改查
数据库为MySQL数据库,Oracle数据库类似: create database db_test;--创建数据库 ';--创建用户 grant all privileges on db_test.* ...
- freemarker跳出循环
break语句跳出当前循环,如下: <#list table.columns as c> <#if c.isPK> &l ...
- HTML5 离线功能介绍
HTML5 是目前正在讨论的新一代 HTML 标准,它代表了现在 Web 领域的最新发展方向.在 HTML5 标准中,加入了新的多样的内容描述标签,直接支持表单验证.视频音频标签.网页元素的拖拽.离线 ...
- './mysql-bin.index' not found (Errcode: 13) 的解决方法
将文件系统复制到PC机上,然后再拷贝到别的SD卡后,发现mysql无法启动了,首先检查了一下mysql的错误日志,发现最后出现以下错误: /usr/local/mysql/libexec/mysqld ...
- Gen_event行为分析和实践
1.简介 Gen_event实现了通用事件处理,通过其提供的标准接口方法以及回调函数,在OTP里面的事件处理模块是由一块通用的事件管理器和任意数量的事件处理器,并且这些事件处理器可以动态的添加和删除. ...
- C# 有关文件路径的操作
1. 由文件全路径,获取文件扩展名.文件名等信息 string fullPath = @"\WebSite1\Default.aspx"; string filename = Sy ...
- 傲游浏览器4,傲游浏览器5如何一键批量打开url链接。
傲游浏览器批量打开网址的插件没用了.有很多网友发了方法也无法实现.实际上,是可以实现傲游浏览器4,傲游浏览器5一键批量打开url链接的.我来告诉大家如何来实现.最新的M5都能使用.在收藏夹添加一个收藏 ...