Kiven

Knowledge Has No Limit And Stick To It All The Time !
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c#/asp.net/html/css/js/jquery 实用小方法 整理笔记

Posted on 2011-11-10 09:02  KivenRo  阅读(3168)  评论(2编辑  收藏  举报
在一个整数数组中随机抽取几个数,并求和
 1  public int GetRandomSum(int[] array,int num)
2 {
3 int count = 0;
4 string ran = "";
5 bool result=false;
6 Random random = new Random();
7 for (int j = 0; j < num; j++)
8 {
9 int len = random.Next(array.Length);
10 if (ran == "")
11 {
12 ran = len + "|";
13 count += array[len] ;
14 num--;
15 }
16 else
17 {
18 string[] ranlist = ran.Split('|');
19 foreach (string rl in ranlist)
20 {
21 if (rl != "")
22 {
23 result = rl == len.ToString() ? false : true;
24 if (!result)
25 {
26 break;
27 }
28 }
29 }
30 }
31
32 if (result)
33 {
34 count += array[len] ;
35 ran += len + "|";
36 }
37 else
38 {
39 num++;
40 }
41 }
42 return count;
43 }

 

将IP转化为一组数字
public static Int64 ConvertIP(string UserIP)
{
string[] ArrayIP = UserIP.Split('.');
string UserIPList = "";
for (int i = 0; i < ArrayIP.Length; i++)
{
if (ArrayIP[i].Length != 0 || int.Parse(ArrayIP[i].ToString()) <= 255)
{
for (int j = 0; j < 3 - ArrayIP[i].Length; j++)
{
UserIPList += "0";
}
UserIPList += ArrayIP[i].ToString();
}
}
return Int64.Parse(UserIPList);
}

 

判断文件或文件夹是否存在,不存在则新建
public static void CheckFile(string file)
{
if(!FileObject.IsExist(file,FsoMethod.Folder))
{
FileObject.Create(file, FsoMethod.Folder);
}
}

 

截取字符串
截取字符串,一个汉字表示两字符(可设置)
参数 str:要截取的字符串     start:开始截取位置     length:截取长度     resvalue:附加字符
    reschatwo:设置一个汉字是否表示两个字符,true为是,false为否
    public static string GetCutString(string str, int start, int length,string resvalue,bool reschatwo)
{
string strvalue = str.ToString();
int i = 0, j = 0;
foreach (char ch in strvalue)
{
if (reschatwo && (int)ch > 172)
{
i += 2;
}
else
{
i++;
}

if (i > length)
{
if (strvalue.Length - start > j)
{
strvalue = strvalue.Substring(start, j);
}
else
{
strvalue = strvalue.Substring(start);
}
break;
}
j++;
}
return strvalue + resvalue;
}
 
截取字符串:将字符串按指定的个数,循环截取成多个字符串
参数 str:要截取的字符串    num:截取的个数    resvalue:返回结果字符串
        public void GetCutString(string str,int num,ref string resvalue)
        {
            if (str.Length % num == 0)
            {
                for (int i = 0, j = 0; j < (str.Length / num + 1); j++, i = i + num)
                {
                    resvalue += str.Substring(i, num)+"<br/>";
                }
            }
            else
            {
                for (int i = 0, j = 0; j < (str.Length / num); j++, i = i + num)
                {
                   resvalue+= str.Substring(i, num)+"<br/>";
                }
                resvalue += str.Substring((str.Length / num) * num, str.Length % num);
            }
        }
 

 

返回16位加密数据
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}

 

对16位加密数据解密
public static string Decrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = Text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}

 

上传图片时,实现图片预览效果 
<script type="text/javascript">    
function getFullPath(obj) {
if (obj) {
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
obj.select();
return document.selection.createRange().text;
}
else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
</script>
onchange="document.getElementById('Photo').src=getFullPath(this)"

 

快速获取上传文件的大小
<script language="javascript" type="text/javascript">

function getFileSize(filePath) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
alert("文件大小为:" + fso.GetFile(filePath).size);
}

</script>
<input id="File1" type="file" onchange="getFileSize(this.value);"/>
似乎会有安全提示!

 

对于AspNetPager分页控件属性设置及样式设置
效果图:

 

aspnetpaper属性设置:

CustomInfoTextAlign="Justify"
FirstPageText="[首页]"
LastPageText="[尾页]"
NextPageText="[下页]"
PrevPageText="[上页]"
AlwaysShow="True"
CustomInfoHTML="第%CurrentPageIndex%页/共%PageCount%页 每页%PageSize%条/共%RecordCount%条"
ShowCustomInfoSection="left"
CurrentPageButtonPosition="Beginning"
NumericButtonCount="5"
ShowBoxThreshold="1"
PageIndexBoxStyle="Text"
PageSize="15"
CustomInfoSectionWidth="63%"
Width="100%"
PageIndexBoxClass="pagewidgettxt"
SubmitButtonClass="pagewidgetsub"
SubmitButtonText="跳转"
ShowMoreButtons="False"
aspnetpaper样式设置:
.pagewidgetsub
{ border:1px solid gray;background:#EBF4FB;width:28px;height:18px; margin-left:3px;}
.pagewidgettxt{ border:1px solid gray;background:white;width:28px;height:16px;}

 

实现验证码无刷新更换
<script src="JS/jquery-1.4.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#Image1").click(function() {
var d = new Date();
$(this).attr("src", "img.aspx?id=" + d);
});
});
</script>

 

实现下载文件调用方法
方法一:
Page.Response.Clear();
FileInfo fi = new FileInfo(Server.MapPath(fileurl));//fullpath指的是文件的物理路径
if (fi.Exists)
{
string type = fileuploadname.Substring(fileuploadname.LastIndexOf("."));
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename + type));//
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream;charset = gb2312";
Response.Filter.Close();
Response.WriteFile(fi.FullName);
Response.End();
}
方法二:
//检测磁盘上的文件是否存在
if (FileObject.IsExist(Server.MapPath("../UploadFile/" + editionurlname), FsoMethod.File))
{
string path = Server.MapPath("../UploadFile/" + editionurlname);

//下载磁盘上的文件
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(editionurlname, System.Text.Encoding.UTF8));
HttpContext.Current.Response.WriteFile(path);
HttpContext.Current.Response.End();

}

 

对中英文混合字符串截取指定长度
    public string getStrLenB(string str, int startidx, int len)
{

int Lengthb = getLengthb(str);

if (startidx + 1 > Lengthb)
{

return "";

}

int j = 0;

int l = 0;

int strw = 0;//字符的宽度

bool b = false;

string rstr = "";

for (int i = 0; i < str.Length; i++)
{

char c = str[i];

if (j >= startidx)
{

rstr = rstr + c;

b = true;

}

if (IsChinese(c))
{

strw = 2;

}

else
{

strw = 1;

}

j = j + strw;

if (b)
{

l = l + strw;

if ((l + 1) >= len) break;

}

}

return rstr;

}

 

对文本框中输入的内容字数进行同意计算
function ShowLeft() {
var LenString, LenStringI, Strings;
LenString = fucCheckLength(document.getElementById("zongjie").value);
LenStringI = LenString;
if (LenString > 2000) {
alert("输入的字符长度不能超过2000(汉字1000个)!");
document.getElementById("l1").innerHTML = "还可输入0个字符";
Strings = document.getElementById("zongjie").value;
while (LenStringI > 2000) {
if ((Strings.charCodeAt(Strings.length) >= 0) && (Strings.charCodeAt(Strings.length) <= 255)) {
LenStringI = LenStringI - 1;
}
else {
LenStringI = LenStringI - 2;
}
Strings = Strings.substring(0, (Strings.length - 1));
}
document.getElementById("zongjie").value = Strings;
return false;
}
document.getElementById("l1").innerHTML = "还可输入" + (2000 - LenString) + "个字符";
}

 

遍历并获取内容中的图片名称
public static ArrayList GetHtmlImageUrlList(string sHtmlText)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(sHtmlText);
ArrayList sUrlList = new ArrayList();

// 取得匹配项列表
foreach (Match match in matches)
{
string url = match.Groups["imgUrl"].Value;
sUrlList.Add(url);
}

return sUrlList;
}

 

判断文件夹是否存在,如果不存在则新建
 //判断文件夹是否存在,如果不存在则新建
        public static void FolderCreate(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

 










-----------------待不断累积--------------------