asp.net 开发常用的方法一

总结asp.net开发常用的方法一

 

using System; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.IO; namespace MoneyWise { /// <summary> /// utils 的摘要说明。 /// </summary> public class utils { private utils() { } public static string ToBin(int source) { int t = source; string ret = ""; for (int i = 0; i < 32; i++) { ret = ((t & 1) == 1 ? "1" : "0") + ret; t >>= 1; } return ret; } public static bool CreateDirs(string path) { for (int i = 0; i < path.Length; i++) { if (path[i] == '//' || path[i] == '/') { if (Directory.CreateDirectory(path.Substring(0, i)).Exists == false) return false; } } Directory.CreateDirectory(path); return true; } public static void CopyDirectory(string SourceDirectory, string TargetDirectory) { if (SourceDirectory[SourceDirectory.Length - 1] == '//' || SourceDirectory[SourceDirectory.Length - 1] == '/') SourceDirectory = SourceDirectory.Substring(0, SourceDirectory.Length - 1); if (TargetDirectory[TargetDirectory.Length - 1] == '//' || TargetDirectory[TargetDirectory.Length - 1] == '/') TargetDirectory = TargetDirectory.Substring(0, TargetDirectory.Length - 1); DirectoryInfo source = new DirectoryInfo(SourceDirectory); DirectoryInfo target = new DirectoryInfo(TargetDirectory); try { //Determine whether the source directory exists. if(!source.Exists) return; if(!target.Exists) target.Create(); //Copy files. FileInfo[] sourceFiles = source.GetFiles(); for(int i = 0; i < sourceFiles.Length; ++i) File.Copy(sourceFiles[i].FullName, target.FullName + "//" + sourceFiles[i].Name,true); //Copy directories. DirectoryInfo[] sourceDirectories = source.GetDirectories(); for(int j = 0; j < sourceDirectories.Length; ++j) CopyDirectory(sourceDirectories[j].FullName,target.FullName +"//" + sourceDirectories[j].Name); } finally { } } public class TDirFile { public bool IsDir; public string name; public TDirFile(bool IsDir, string name) { this.IsDir = IsDir; this.name = name; } } public static void GetDirFile(string SourceDirectory, string relative, ArrayList list) { //去最后一个/ char last = SourceDirectory[SourceDirectory.Length - 1]; if (last == '/' || last == '//') { SourceDirectory = SourceDirectory.Substring(0, SourceDirectory.Length - 1); } DirectoryInfo source = new DirectoryInfo(SourceDirectory); //Determine whether the source directory exists. if(!source.Exists) return; FileInfo[] sourceFiles = source.GetFiles(); for(int i = 0; i < sourceFiles.Length; ++i) list.Add(new TDirFile(false, (relative == "" ? "" : (relative + "/")) + sourceFiles[i].Name)); DirectoryInfo[] sourceDirectories = source.GetDirectories(); for(int j = 0; j < sourceDirectories.Length; ++j) { list.Add(new TDirFile(true, (relative == "" ? "" : (relative + "/")) + sourceDirectories[j].Name)); } for(int j = 0; j < sourceDirectories.Length; ++j) { GetDirFile(SourceDirectory + "/" + sourceDirectories[j].Name, (relative == "" ? "" : (relative + "/")) + sourceDirectories[j].Name, list); } } /// <summary> /// 将路径的第一个和最后一个//去掉 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FormatPath(string path) { if (path[0] == '/' || path[0] == '//') { path = path.Substring(1, path.Length - 1); } if (path[path.Length - 1] == '/' || path[path.Length - 1] == '//') { path = path.Substring(0, path.Length - 1); } return path; } public static string GetPath(int id) { string ret = ""; string temp = id.ToString(); if (temp.Length % 2 == 1) temp = "0" + temp; for (int i = 0; i < temp.Length; i += 2) { ret = ret + temp.Substring(i,2) + "/"; } return ret; } public static void RemoveReadOnlyAttr(string file) { try { if (File.Exists(file)) File.SetAttributes(file, FileAttributes.Normal); } catch { } } public static string FormatDate(DateTime date) { int y,m,d,h,mi,s,z; y = date.Year; m = date.Month; d = date.Day; h = date.Hour; mi = date.Minute; s = date.Second; z = date.Millisecond; return string .Format("{0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}{6:000}", new object[]{y,m,d,h,mi,s,z}); } public static string FormatDate() { return FormatDate(DateTime.Now); } /// <summary> /// 截止指定长度的字符串 /// </summary> /// <param name="inputString">字符串</param> /// <param name="len">长度</param> /// <returns>返回截止后的字符串</returns> public static string SubStr(string inputString,int len) { CharEnumerator ce = inputString.GetEnumerator(); int length = 0; string result = ""; while(ce.MoveNext()) { if (length >= len) break; switch(Char.GetUnicodeCategory(ce.Current)) { case UnicodeCategory.LetterNumber: length++; break; case UnicodeCategory.OtherLetter: length += 2; break; default: length += ce.Current > 255 ? 2 : 1; break; } result += ce.Current; } return result.Length == inputString.Length ? result : result + "..."; } public static string GetConstellation(string birthday) { return GetConstellation(Convert.ToDateTime(birthday)); } /// <summary> /// 得到星座序列,从白羊(3.21)开始 /// </summary> public static string GetConstellation(DateTime birthday) { string tmpstr = birthday.ToString("MM-dd"); string str = ""; if ((tmpstr.CompareTo("03-21")>=0) & (tmpstr.CompareTo("04-19")<=0)) { str = "1"; } if ((tmpstr.CompareTo("04-20")>=0) & (tmpstr.CompareTo("05-20")<=0)) { str = "2"; } if ((tmpstr.CompareTo("05-21")>=0) & (tmpstr.CompareTo("06-21")<=0)) { str = "3"; } if ((tmpstr.CompareTo("06-22")>=0) & (tmpstr.CompareTo("07-22")<=0)) { str = "4"; } if ((tmpstr.CompareTo("07-23")>=0) & (tmpstr.CompareTo("08-22")<=0)) { str = "5"; } if ((tmpstr.CompareTo("08-23")>=0) & (tmpstr.CompareTo("09-22")<=0)) { str = "6"; } if ((tmpstr.CompareTo("09-23")>=0) & (tmpstr.CompareTo("10-23")<=0)) { str = "7"; } if ((tmpstr.CompareTo("10-24")>=0) & (tmpstr.CompareTo("11-22")<=0)) { str = "8"; } if ((tmpstr.CompareTo("11-23")>=0) & (tmpstr.CompareTo("12-21")<=0)) { str = "9"; } if ((tmpstr.CompareTo("12-22")>=0) & (tmpstr.CompareTo("12-31")<=0)) { str = "10"; } if ((tmpstr.CompareTo("01-01")>=0) & (tmpstr.CompareTo("01-19")<=0)) { str = "10"; } if ((tmpstr.CompareTo("01-20")>=0) & (tmpstr.CompareTo("02-18")<=0)) { str = "11"; } if ((tmpstr.CompareTo("02-19")>=0) & (tmpstr.CompareTo("03-20")<=0)) { str = "12"; } return str; } /// <summary> /// HTML编码 /// </summary> /// <param name="content">要进行编码的字符串</param> /// <returns>返回编码后的字符串</returns> public static string HTMLEncode(string content) { content = HTMLEncodeLite(content); if ((content != null) && (content != String.Empty)) { content = content.Replace("/r/n","/n"); content = content.Replace("/n","<br/>"); } return content; } /// <summary> /// HTML编码简化版 /// </summary> /// <param name="content">要进行编码的字符串</param> /// <returns>返回编码后的字符串</returns> public static string HTMLEncodeLite(string content) { if ((content != null) && (content != String.Empty)) { content = content.Replace("&","&"); content = content.Replace("<","<"); content = content.Replace(">",">"); content = content.Replace("'","'"); //单引号 content = content.Replace("/"","""); //双引号 } return content; } /// <summary> /// HTML反编码 /// </summary> /// <param name="content">要进行反编码的字符串</param> /// <returns>返回反编码后的字符串</returns> public static string HTMLDecode(string content) { if ((content != null) && (content != String.Empty)) { content = content.Replace("<","<"); content = content.Replace(">",">"); content = content.Replace("'","'"); content = content.Replace(""","/""); content = content.Replace("&","&"); Regex.Replace(content, "<br//s*/>", "/r/n", RegexOptions.IgnoreCase); } return content; } public static void DeleteTree(string root) { Directory.Delete(root, true); } /// <summary> /// 注意:Content应该是允许包含HTML代码的字符串 /// </summary> /// <param name="Content"></param> /// <returns></returns> public static string GetSummery(string Content) { return GetSummery(Content, 200); } /// <summary> /// 注意:Content应该是允许包含HTML代码的字符串 /// </summary> /// <param name="Content"></param> /// <param name="SummeryLen"></param> /// <returns></returns> public static string GetSummery(string Content, int SummeryLen) { string Summery = ""; if (Content.Length > SummeryLen) { bool find = false; for (int j = SummeryLen; j < Content.Length; j++) { if (Content[j] == '<') { Summery = Content.Substring(0, SummeryLen); find = true; break; } else if (Content[j] == '>') { Summery = Content.Substring(0, j + 1); find = true; break; } } if (!find) Summery = Content.Substring(0, SummeryLen); int count = 0; int mostright = Summery.Length; for (int i = 0; i < Summery.Length - 7; i++) { if (Summery.Substring(i, 6).Equals("<TABLE")) { if (count == 0) mostright = i; count++; } else if (Summery.Substring(i, 7).Equals("</TABLE")) { count--; if (count == 0) mostright = i + 1; } } if (count != 0) { Summery = Summery.Substring(0, mostright); } else { count = 0; mostright = Summery.Length; for (int i = 0; i < Summery.Length - 8; i++) { if (Summery.Substring(i, 7).Equals("<OBJECT")) { if (count == 0) mostright = i; count++; } else if (Summery.Substring(i, 8).Equals("</OBJECT")) { count--; if (count == 0) mostright = i + 1; } } if (count != 0) { Summery = Summery.Substring(0, mostright); } else { } } Summery += "..."; } else { Summery = Content; } return Summery; } /// <summary> /// 重载HTML编码截取固定长度 /// </summary> /// <param name="Content">原HTML内容</param> /// <param name="SummeryLen">截取字数</param> /// <param name="SummeryEnd">截取后在末尾添加文字</param> /// <returns></returns> public static string GetSummery(string Content, int SummeryLen, string SummeryEnd) { return GetSummery(Content, SummeryLen, SummeryEnd, true); } /// <summary> /// 重载HTML编码截取固定长度(内容,不包含HTML标签) /// </summary> /// <param name="Content">原HTML内容</param> /// <param name="SummeryLen">截取字节长度</param> /// <param name="SummeryEnd">截取后在末尾添加文字</param> /// <param name="IncludePic">是否包含图片</param> /// <returns></returns> public static string GetSummery(string Content, int SummeryLen, string SummeryEnd, bool IncludePic) { StringBuilder result = new StringBuilder(); int n = 0; char temp; bool isCode = false; //是不是HTML代码 bool isHTML = false; //是不是HTML特殊字符,如  for (int i = 0; i < Content.Length; i++) { temp = Content[i]; if (temp == '<') { isCode = true; } else if (temp == '&') { isHTML = true; } else if (temp == '>' && isCode) { n = n - 1; isCode = false; } else if (temp == ';' && isHTML) isHTML = false; if (!isCode && !isHTML) n += temp > 255 ? 2 : 1; result.Append(temp); if (n >= SummeryLen) { result.Append(SummeryEnd); break; } } //取出截取字符串中的HTML标记 //string temp_result = result.ToString().Replace("(>)[^<>]*(<?)", "$1$2"); string temp_result = Regex.Replace(result.ToString(), "(>)[^<>]*(<?)", "$1$2"); //去掉不需要结素标记的HTML标记 //temp_result = temp_result.Replace("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", ""); temp_result = Regex.Replace(temp_result, "</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", ""); //去掉成对的HTML标记 //temp_result=temp_result.Replace(@"<([a-zA-Z]+)[^<>]*>(.*?)<//1>","$2"); string temp_HTML = temp_result; //此正则替换无法做到递归替换,无法处理嵌套HTML元素。 //这里加一个循环来处理嵌套HTML元素问题。By马克维,08-01-07 do { temp_result = temp_HTML; temp_HTML= Regex.Replace(temp_result, @"<([a-zA-Z]+)[^<>]*>(.*?)<//1>","$2"); } while(temp_HTML != temp_result); //用正则表达式取出标记 string p = ("<([a-zA-Z]+)[^<>]*>"); MatchCollection m = Regex.Matches((temp_result), p); ArrayList endHTML = new ArrayList(); for(int i = 0; i < m.Count; i++) { endHTML.Add(m[i].Result("$1")); } //补全不成对的HTML标记 for (int i = endHTML.Count - 1; i >= 0; i--) { result.Append("</"); result.Append(endHTML[i]); result.Append(">"); } string ret = result.ToString(); if(!IncludePic) { ret = Regex.Replace(ret, "<(IMG|img)[^<>]*/?>", ""); ret = Regex.Replace(ret, "<(INPUT|input)[^<>]*(TYPE|type)=/"(IMAGE|image)/"[^<>]*/?>", ""); } return ret; } /// <summary> /// 截取固定长度的字符串(去除HTML标签) /// </summary> /// <param name="html">输入字符串</param> /// <param name="count">截取长度,负数为不截取(-1)</param> /// <param name="eclipse">截取后结尾字符</param> /// <param name="replaceCRLN">是否替换换行</param> public static string GetSummaryWithoutHTML(string html, int count, string eclipse, bool replaceCRLN) { html = Regex.Replace(html, @"<[/s]*script[^>]*?>[/s/S]*?<[/s]*?//[/s]*?script[/s]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline); html = Regex.Replace(html, @"<[/s]*style[^>]*?>[/s/S]*?<[/s]*?//[/s]*?style[/s]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline); html = Regex.Replace(html, @"(/40*<br[/40]*/?>)+", "/r/n", RegexOptions.IgnoreCase); if(replaceCRLN) html = Regex.Replace(html, @"(/r/n|/n)+", " "); html = Regex.Replace(html, @"/40+", " "); bool tag = false; bool tagDef = false; bool attr1 = false; bool attr2 = false; bool entity = false; bool space = false; //bool script = false; //bool style = false; string temp = ""; StringBuilder sb = new StringBuilder(); int j = 0; for (int i = 0; i < html.Length; i++) { if (count > 0 && j >= count && html.Length - i > eclipse.Length) { sb.Append(eclipse); break; } if (html[i] == ' ' || html[i] == '/t') { if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (tagDef && temp.Length > 0) tagDef = false; if (!tag && !space) { sb.Append(' '); j++; } space = true; continue; } else space = false; switch (html[i]) { case '<': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (!tag) { tag = true; tagDef = true; temp = ""; } else { sb.Append("<"); j++; } break; case '/': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (tag && !attr1 && !attr2 && temp.Length > 0) tagDef = false; else if (!tag) { sb.Append('/'); j++; } break; case '>': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (tag && !attr1 && !attr2) { switch (temp.ToLower()) { case "br": sb.Append(" "); j++; break; /* 改用正则表达式提前处理 case "script": script = !script; break; case "style": style = !style; break; */ } tag = false; tagDef = false; } else if (!tag) { sb.Append(">"); j++; } break; case '/'': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (tag && !attr2) attr1 = !attr1; if (!tag) { sb.Append('/''); j++; } break; case '"': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (tag && !attr1) attr2 = !attr2; if (!tag) { sb.Append("""); j++; } break; case '&': if (entity) { entity = false; i = i - temp.Length - 1; sb.Append("&"); j++; continue; } if (!tag) { entity = true; temp = ""; } if (tagDef) temp += html[i]; break; case ';': if (entity) { entity = false; if (temp.Length > 0) { sb.Append('&'); sb.Append(temp); } else sb.Append("&"); sb.Append(';'); j++; } else if (!tag) { sb.Append(';'); j++; } break; default: if (tagDef) temp += html[i]; if (entity) { temp += html[i]; if (temp.Length > 6 || html[i] == '/r' || html[i] == '/n') { entity = false; i = i - temp.Length; sb.Append("&"); j++; continue; } } if (!tag && !entity) { sb.Append(html[i]); if (html[i] == '/r' && html.Length - 1 > i && html[i + 1] == '/n') j += 0; else j += html[i] > 255 ? 2 : 1; } break; } } if (entity && j < count) { sb.Append("&"); if (temp.Length > 0) sb.Append(temp); } return sb.ToString(); } /// <summary> /// 获取HTML编码中的第一张图片地址 /// </summary> /// <param name="Content">HTML编码内容</param> /// <returns></returns> public static string GetFirstPicAddr(string Content) { string Patten = "<((IMG|img)|((INPUT|input)[^<>]*(TYPE|type)=/"(IMAGE|image)/"))[^<>]*(SRC|src)=/"(.*?)/"[^<>]*/?>"; //System.Text.RegularExpressions.Match m = Regex.Match(Content, Patten); MatchCollection m = Regex.Matches(Content, Patten); string ret = ""; for(int i = 0; i < m.Count; i++) { if(m[i].Success) { if(m[i].Result("$8").IndexOf("images/smiley") < 0) { ret = m[i].Result("$8"); break; } } } //if(m.Success) // ret = m.Result("$8"); return ret; } /// <summary> /// 验证是否是非负整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsInt(string str) { if (str != null && str != string.Empty) return Regex.IsMatch(str, @"^/d+$"); return false; } /// <summary> /// 从文件中读出字符串 /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string GetStringFromFile(string filename) { string strInput; StreamReader sr = new StreamReader(filename, Encoding.GetEncoding(936)); try { strInput = sr.ReadToEnd(); } finally { sr.Close(); } return strInput; } /// <summary> /// 获得文件名,无扩展名 /// </summary> public static string GetFileNameNoEx(string filename) { filename = Path.ChangeExtension(filename, ""); return filename.Remove(filename.Length - 1, 1); } /// <summary> /// 获取HTML内容(博客文章等)的实际字数 /// 暂时未将英文单词区分(目前一个英文字母算做一字儿) /// </summary> /// <param name="temp"></param> /// <returns></returns> public static int GetContentLength(string temp) { temp = Regex.Replace(temp, @"//r//n", ""); MatchCollection mc = Regex.Matches(temp, ">([^<>]*)<?"); StringBuilder sb = new StringBuilder(); if(mc.Count > 0) { for(int i=0; i<mc.Count; i++) { sb.Append(mc[i].Result("$1").ToString()); } temp = sb.ToString(); temp = Regex.Replace(temp, @"<", "<"); temp = Regex.Replace(temp, @">", ">"); temp = Regex.Replace(temp, @""", "/""); temp = Regex.Replace(temp, @"<(?:[a-zA-Z/]+)[^<>]*>", "的"); temp = Regex.Replace(temp, @"/s| ", ""); } return temp.Length; } /// <summary> /// 获取0到某值范围内的指定数量的随机数数组 /// </summary> /// <param name="count">获取数量</param> /// <param name="libcount">样本库最大值</param> /// <returns></returns> public static int[] GetRandomList(int count, int libcount) { if(libcount <= 0 || count > libcount) return null; int[] Lib = new int[libcount]; int[] ret = new int[count]; for(int i = 0; i < libcount; i++) { Lib[i] = i; } Random rd = new Random(); int temp; int idx; for(int i = 0; i < count; i++) { idx = rd.Next(0, libcount - 1); temp = Lib[idx]; Lib[idx] = Lib[i]; Lib[i] = temp; } for(int i = 0; i < count; i++) { ret[i] = Lib[i]; } return ret; } /// <summary> /// 将http://,https://,www,ftp://开头的替换为<a></a> /// </summary> /// <param name="content"></param> /// <returns></returns> public static string ReplaceLink(string content) { string temp = content; temp = Regex.Replace(temp, @"((www/.|https://www|http://www|ftp://www|https://|http://|ftp://)[a-zA-Z0-9+=%?&#_/:/./;/-///|@!~$]+)", "<a href="$1" mce_href="$1" style="text-decoration:underline" mce_style="text-decoration:underline" target='_blank'>$1</a>", RegexOptions.IgnoreCase); temp = Regex.Replace(temp, @"href='(www[a-zA-Z0-9+=%?&#_/:/./;/-///|@!~$]+)'?", "href='http://$1'", RegexOptions.IgnoreCase); return temp; } /// <summary> /// 自动检测URL链接 /// </summary> public static string AutoDetectLink(string content) { content = Regex.Replace(content, @"((ht|f)tps?:////|www/.)([a-zA-Z0-9_-]+/.)+[a-zA-Z0-9_:-]+(//[a-zA-Z0-9_.//?%#&;=+-~]*)*", "<a target='_blank' href="$0" mce_href="$0">$0</a>"); return Regex.Replace(content, "(href=')(www[.])", "$1http://$2"); } } }

你可能感兴趣的:(html,正则表达式,String,asp.net,input,Path)