Hopes

Start Here..

 

C# 常用自定义方法




    
/// <summary>
    
/// 进行对字符串解析
    
/// </summary>
    
/// <param name="inputString"></param>
    
/// <returns></returns>
    public static string InputText(string inputString)
    {
        StringBuilder retVal 
= new StringBuilder();

        
// check incoming parameters for null or blank string
        if ((inputString != null&& (inputString != String.Empty))
        {
            inputString 
= HttpUtility.HtmlEncode(inputString.Trim());

            
//chop the string incase the client-side max length
            
//fields are bypassed to prevent buffer over-runs
            
//                if (inputString.Length > maxLength)
            
//                    inputString = inputString.Substring(0, maxLength);

            
//convert some harmful symbols incase the regular
            
//expression validators are changed
            for (int i = 0; i < inputString.Length; i++)
            {
                
switch (inputString[i])
                {
                    
case '"':
                        retVal.Append(
"&quot;");
                        
break;
                    
case '<':
                        retVal.Append(
"&lt;");
                        
break;
                    
case '>':
                        retVal.Append(
"&gt;");
                        
break;
                    
default:
                        retVal.Append(inputString[i]);
                        
break;
                }
            }
            
// Replace single quotes with white space
            retVal.Replace("'"" ");
        }
        
return retVal.ToString();
    }

    
public static bool DataSetIsNull(DataSet ds)
    {
        
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            
return true;
        
else
            
return false;
    }

    
//public static string GetPicByVideoName(string s)
    
//{
    
//    return "http://www.seehaha.com/vandp/" + s.ToLower().Replace("flv", "jpg");
    
//}


    
public static void ShowMessage(Page p, string strmessage)
    {
        
string strScript = "<script>alert('" + strmessage + "');</script>";
        p.ClientScript.RegisterClientScriptBlock(p.GetType(), 
"script", strScript);
    }

    
public static void ShowMessage(Page p, string strmessage, string url)
    {
        
string strScript = "<script>alert('" + strmessage + "');window.location='" + url + "'</script>";
        p.ClientScript.RegisterClientScriptBlock(p.GetType(), 
"script", strScript);
    }

    
//得到登录员工所在公司ID
    public static string getLoginCompanyId(Page p)
    {
        
object cID = p.Request.Cookies["CompanyID"].Value;
        
if (cID == null)
            
return "0";
        
else
            
return cID.ToString();
    }

    
////得到登录员工角色代码
    //public static string getLoginRoleCode(Page p)
    
//{
    
//    object scode = p.Request.Cookies["SearchCode"].Value;
    
//    if (scode == null)
    
//        return "0";
    
//    else
    
//        return scode.ToString();
    
//}


    
/// <summary>
    
/// 按字节数截取字符串
    
/// </summary>
    
/// <param name="origStr">原始字符串</param>
    
/// <param name="endIndex">提取前endIdex个字节</param>
    
/// <returns></returns>    
    //public static string GetSubString(string origStr, int endIndex)
    
//{
    
//    /*byte[] bytes=System.Text.Encoding.GetEncoding("gb2312").GetBytes(origStr);
    
//    //如果提取长度大于或等于原始字符串长度,直接返回原始字符串
    
//    if(endIndex>=bytes.Length)
    
//        return origStr;
    
//    byte[] subBytes=new byte[endIndex];
    
//    Array.Copy(bytes,0,subBytes,0,endIndex);
    
//    return System.Text.Encoding.GetEncoding("gb2312").GetString(subBytes)+"";*/
    
//    if (origStr == null || origStr.Length == 0 || endIndex < 0)
    
//        return "";
    
//    int bytesCount = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(origStr);
    
//    if (bytesCount > endIndex)
    
//    {
    
//        int readyLength = 0;
    
//        int byteLength;
    
//        for (int i = 0; i < origStr.Length; i++)
    
//        {
    
//            byteLength = System.Text.Encoding.GetEncoding("gb2312").GetByteCount(new char[] { origStr[i] });
    
//            readyLength += byteLength;
    
//            if (readyLength == endIndex)
    
//            {
    
//                origStr = origStr.Substring(0, i + 1) + "";
    
//                break;
    
//            }
    
//            else if (readyLength > endIndex)
    
//            {
    
//                origStr = origStr.Substring(0, i) + "";
    
//                break;
    
//            }
    
//        }
    
//    }

    
//    return origStr;
    
//}


    
public static string OutputText(string inputString)
    {
        StringBuilder retVal 
= new StringBuilder();

        
// check incoming parameters for null or blank string
        if ((inputString != null&& (inputString != String.Empty))
        {
            inputString 
= HttpUtility.HtmlDecode(inputString.Trim());

            
//chop the string incase the client-side max length
            
//fields are bypassed to prevent buffer over-runs
            
//                if (inputString.Length > maxLength)
            
//                    inputString = inputString.Substring(0, maxLength);

            
//convert some harmful symbols incase the regular
            
//expression validators are changed

            
// Replace single quotes with white space

        }
        
return inputString;
    }

    
//执行脚本
    public static void exeScriptText(Page p, string sScipt)
    {
        
string strScript = "<script>" + sScipt + ";</script>";
        p.ClientScript.RegisterClientScriptBlock(p.GetType(), 
"scriptText", strScript);
    }




    
public static string getCdate(object CDate)
    {
        DateTime TempDate 
= (DateTime)CDate;

        
return TempDate.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo);
    }

    
//public static string getVideoFileName(string sDate)
    
//{


    
//    sDate = sDate.ToLower();

    
//    sDate = sDate.Replace(".flv", "");

    
//    string tempPic = sDate;

    
//    if (Test(sDate))
    
//    {
    
//        tempPic = sDate;

    
//    }
    
//    else
    
//    {
    
//        tempPic = "http://vandp.seehaha.com/" + sDate.Substring(29, sDate.Length - 29);

    
//        if (Test(tempPic))
    
//        {
    
//            tempPic = "images/novideopic.jpg";
    
//        }

    
//    }


    
//    return sDate;
    
//}






    
//public static string getVideoPic(string Pic)
    
//{
    
//    Pic = Pic.ToLower().Replace(".flv", "");

    
//    string tempPic = Pic;

    
//    if (Pic.Length < 29)
    
//    {
    
//        tempPic = "images/novideopic.jpg";

    
//    }
    
//    else
    
//    {
    
//        tempPic = "http://vandp.seehaha.com/" + Pic.Substring(29, Pic.Length - 29);
    
//    }

    
//    return tempPic;

    
//}


    
private static bool Test(string URL)
    {
        
try
        {
            System.Net.WebRequest s 
= System.Net.WebRequest.Create(URL);
            s.Timeout 
= 10000;//响应时间  
            System.Net.WebResponse a = s.GetResponse();
            
return true;
        }
        
catch
        {
            
return false;
        }
    }


    
public static bool SendEmail(string toEmail, string sTitle, string sContent)
    {

        
string sMailServer = "smtp.163com";
        
string sReplayEmail = "xoyuer@163.com";
        
string sSmtpAccount = "xoyuer";
        
string sSmtpPwd = "motomo";




        MailMessage myMail 
= new MailMessage();
        myMail.From 
= sReplayEmail;
        myMail.To 
= toEmail;

        myMail.Subject 
= sTitle;
        myMail.Priority 
= MailPriority.High;
        myMail.BodyFormat 
= MailFormat.Text;
        
//myMail.BodyFormat = MailFormat.Html;         
        myMail.Body = sContent;

        myMail.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate""1");
        myMail.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendusername", sSmtpAccount);
        myMail.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword", sSmtpPwd);

        SmtpMail.SmtpServer 
= sMailServer;
        
try
        {
            SmtpMail.Send(myMail);
        }
        
catch
        {
            
return false;
        }
        
return true;
    }

    
public static void DelTemp()
    {
        
string tempPath = ConfigurationManager.AppSettings["XmlPath"+ "temp";
        DirectoryInfo dir 
= new DirectoryInfo(tempPath);
        
if (dir.Exists)
        {
            
foreach (FileInfo file in dir.GetFiles())
            {
                
if (file.CreationTime.Date.AddDays(3.00== DateTime.Now.Date.AddDays(1.00))
                {
                    file.Delete();
                }
            }
        }
    }

    
public static bool ReqNotNull(Page p, string pid)
    {
        
if (p.Request.QueryString[pid] != null)
        {
            
return true;
        }
        
else
        {
            
return false;
        }
    }
    
public static string ReqV(Page p, string pid)
    {
        
return p.Request.QueryString[pid].ToString();
    }

    
public static string GetSmallPath(string smallname)
    {
        
string path = sSmallPath + smallname;
        
if (!File.Exists(HttpContext.Current.Server.MapPath("./"+ path))
            path 
= sSmallPath + "logo.gif";
        
return path;
    }

    
public static string GetManageSmallPath(string smallname)
    {
        
string path = sSmallPath + smallname;
        
if (!File.Exists(HttpContext.Current.Server.MapPath("../"+ path))
            path 
= sSmallPath + "logo.gif";
        
return "../" + path;
    }

    
public static string GetSamllPathById(int photoId)
    {
        
string path = sSmallPath + "logo.gif";
        
if (photoId != -1)
        {
            
string smallname = new AlbumManager().GetSmallNameById(photoId);
            path 
= sSmallPath + smallname;
            
if (!File.Exists(HttpContext.Current.Server.MapPath("./"+ path))
            {
                path 
= sSmallPath + "logo.gif";
            }
        }
        
return path;
    }

    
public static string GetFace(int albumId)
    {
        
string path = "";
        
int i = new AlbumManager().GetCountByalbum(albumId);
        
if (i > 0)
        {
            
string smallname = new AlbumManager().GetDefalutFaceByalbum(albumId);
            path 
= sSmallPath + smallname;
        }
        
else
        {
            path 
= sSmallPath + "logo.gif";
        }
        
return path;
    }

    
public static string GetVideoPic(string spath)
    {
        
string pathStr = VideoPicPath + "logovideo.gif";
        
if (spath != null && spath != "")
        {
            spath 
= spath.Replace(".flv""");
            spath 
= spath.Substring(spath.LastIndexOf(@"/"+ 1);
            pathStr 
= VideoPicPath + spath + ".jpg";

            
if (!File.Exists(HttpContext.Current.Server.MapPath("./"+ pathStr))
            {
                pathStr 
= VideoPicPath + "logovideo.gif";
            }
        }

        
return pathStr;
    }

    
public static string GetManageVideoPic(string spath)
    {
        
string pathStr = VideoPicPath + "logovideo.gif";
        
if (spath != null && spath != "")
        {
            spath 
= spath.Replace(".flv""");
            spath 
= spath.Substring(spath.LastIndexOf(@"/"+ 1);
            pathStr 
= VideoPicPath + spath + ".jpg";

            
if (!File.Exists(HttpContext.Current.Server.MapPath("../"+ pathStr))
            {
                pathStr 
= VideoPicPath + "logovideo.gif";
            }
        }

        
return "../" + pathStr;
    }

    
public static string GetVideoPath(string spath)
    {
        
string pathStr = "";
        
if (spath != "")
        {
            
string p = spath.Replace(".flv""");

            
if (File.Exists(HttpContext.Current.Server.MapPath("./"+ spath))
            {
                pathStr 
= "../" + p;
            }
        }
        
return pathStr;
    }

    
public static string GetManageVideoPath(string spath)
    {
        
string pathStr = "";
        
if (spath != "")
        {
            
string p = spath.Replace(".flv""");

            
if (File.Exists(HttpContext.Current.Server.MapPath("../"+ spath))
            {
                pathStr 
= "../" + p;
            }
        }
        
return pathStr;
    }

    
/// <summary>
    
/// 截取字符长度(考虑中英文)
    
/// </summary>
    
/// <param name="o"></param>
    
/// <param name="length"></param>
    
/// <returns></returns>
    public static string GetSubString(string tempstring, int length)
    {
        
string temp = tempstring;
        
int j = 0;
        
int k = 0;
        
for (int i = 0; i < temp.Length; i++)
        {
            
if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
            {
                j 
+= 2;
            }
            
else
            {
                j 
+= 1;
            }
            
if (j <= length)
            {
                k 
+= 1;
            }
            
if (j >= length)
            {
                
return temp.Substring(0, k) + "";
            }
        }
        
return temp;
    }

    
/// <summary>
    
/// 截取字符长度(考虑中英文)
    
/// </summary>
    
/// <param name="o"></param>
    
/// <param name="length"></param>
    
/// <returns></returns>
    public static string GetSubStringNoPoint(string tempstring, int length)
    {
        
string temp = tempstring;
        
int j = 0;
        
int k = 0;
        
for (int i = 0; i < temp.Length; i++)
        {
            
if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
            {
                j 
+= 2;
            }
            
else
            {
                j 
+= 1;
            }
            
if (j <= length)
            {
                k 
+= 1;
            }
            
if (j >= length)
            {
                
return temp.Substring(0, k);
            }
        }
        
return temp;

    }

    
public string encode(string str)
    {
        
string htext = "";

        
for (int i = 0; i < str.Length; i++)
        {
            htext 
= htext + (char)(str[i] + 5 - 1 * 2);
        }
        
return htext;
    }

    
public string decode(string str)
    {
        
string dtext = "";

        
for (int i = 0; i < str.Length; i++)
        {
            dtext 
= dtext + (char)(str[i] - 10 + 1 * 2);
        }
        
return dtext;
    }

    
public static void convertSwf(string strFile)
    {
        Process p 
= new Process();
        p.StartInfo.FileName 
= "cmd.exe";
        p.StartInfo.UseShellExecute 
= false;
        p.StartInfo.RedirectStandardInput 
= true;
        p.StartInfo.RedirectStandardOutput 
= true;
        p.StartInfo.RedirectStandardError 
= true;
        p.StartInfo.CreateNoWindow 
= true;
        p.Start();
        
string strOutput = null;
        p.StandardInput.WriteLine(
string.Format(strFile));
        p.StandardInput.WriteLine(
"exit");
        strOutput 
= p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        p.Close();
    }

    
/// <summary>
    
/// 过滤HTML中的不安全标签
    
/// </summary>
    
/// <param name="content"></param>
    
/// <returns></returns>
    public static string RemoveUnsafeHtml(string content)
    {
        content 
= Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)""$1$2", RegexOptions.IgnoreCase);
        content 
= Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+""$1.$2", RegexOptions.IgnoreCase);
        
return content;
    }

    
/// <summary>
    
/// 分割字符串
    
/// </summary>
    public static string[] SplitString(string strContent, string strSplit)
    {
        
if (!Utility.StrIsNullOrEmpty(strContent))
        {
            
if (strContent.IndexOf(strSplit) < 0)
            {
                
string[] tmp = { strContent };
                
return tmp;
            }
            
return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }
        
else
        {
            
return new string[0] { };
        }
    }

    
/// <summary>
    
/// 将对象转换为Int32类型
    
/// </summary>
    
/// <param name="expression">要转换的字符串</param>
    
/// <param name="defValue">缺省值</param>
    
/// <returns>转换后的int类型结果</returns>
    public static int StrToInt(object expression, int defValue)
    {
        
return TypeParse.StrToInt(expression, defValue);
    }

    
/// <summary>
    
/// 从字符串的指定位置截取指定长度的子字符串
    
/// </summary>
    
/// <param name="str">原字符串</param>
    
/// <param name="startIndex">子字符串的起始位置</param>
    
/// <param name="length">子字符串的长度</param>
    
/// <returns>子字符串</returns>
    public static string CutString(string str, int startIndex, int length)
    {
        
if (startIndex >= 0)
        {
            
if (length < 0)
            {
                length 
= length * -1;
                
if (startIndex - length < 0)
                {
                    length 
= startIndex;
                    startIndex 
= 0;
                }
                
else
                {
                    startIndex 
= startIndex - length;
                }
            }


            
if (startIndex > str.Length)
            {
                
return "";
            }


        }
        
else
        {
            
if (length < 0)
            {
                
return "";
            }
            
else
            {
                
if (length + startIndex > 0)
                {
                    length 
= length + startIndex;
                    startIndex 
= 0;
                }
                
else
                {
                    
return "";
                }
            }
        }

        
if (str.Length - startIndex < length)
        {
            length 
= str.Length - startIndex;
        }

        
return str.Substring(startIndex, length);
    }

    
/// <summary>
    
/// 判断指定字符串在指定字符串数组中的位置
    
/// </summary>
    
/// <param name="strSearch">字符串</param>
    
/// <param name="stringArray">字符串数组</param>
    
/// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
    
/// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
    public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
    {
        
for (int i = 0; i < stringArray.Length; i++)
        {
            
if (caseInsensetive)
            {
                
if (strSearch.ToLower() == stringArray[i].ToLower())
                {
                    
return i;
                }
            }
            
else
            {
                
if (strSearch == stringArray[i])
                {
                    
return i;
                }
            }

        }
        
return -1;
    }

    
/// <summary>
    
/// 字段串是否为Null或为""(空)
    
/// </summary>
    
/// <param name="str"></param>
    
/// <returns></returns>
    public static bool StrIsNullOrEmpty(string str)
    {
        
//#if NET1
        if (str == null || str.Trim() == "")
        {
            
return true;
        }
        
//#else
        
//            if (string.IsNullOrEmpty(str))
        
//            {
        
//                return true;
        
//            }
        
//#endif

        
return false;
    }

    
/// <summary>
    
/// 判断指定字符串是否属于指定字符串数组中的一个元素
    
/// </summary>
    
/// <param name="strSearch">字符串</param>
    
/// <param name="stringArray">字符串数组</param>
    
/// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
    
/// <returns>判断结果</returns>
    public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
    {
        
return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
    }

    
/// <summary>
    
/// 判断指定字符串是否属于指定字符串数组中的一个元素
    
/// </summary>
    
/// <param name="str">字符串</param>
    
/// <param name="stringarray">字符串数组</param>
    
/// <returns>判断结果</returns>
    public static bool InArray(string str, string[] stringarray)
    {
        
return InArray(str, stringarray, false);
    }

    
/// <summary>
    
/// 判断指定字符串是否属于指定字符串数组中的一个元素
    
/// </summary>
    
/// <param name="str">字符串</param>
    
/// <param name="stringarray">内部以逗号分割单词的字符串</param>
    
/// <returns>判断结果</returns>
    public static bool InArray(string str, string stringarray)
    {
        
return InArray(str, SplitString(stringarray, ","), false);
    }

    
/// <summary>
    
/// 判断指定字符串是否属于指定字符串数组中的一个元素
    
/// </summary>
    
/// <param name="str">字符串</param>
    
/// <param name="stringarray">内部以逗号分割单词的字符串</param>
    
/// <param name="strsplit">分割字符串</param>
    
/// <returns>判断结果</returns>
    public static bool InArray(string str, string stringarray, string strsplit)
    {
        
return InArray(str, SplitString(stringarray, strsplit), false);
    }

    
/// <summary>
    
/// 判断指定字符串是否属于指定字符串数组中的一个元素
    
/// </summary>
    
/// <param name="str">字符串</param>
    
/// <param name="stringarray">内部以逗号分割单词的字符串</param>
    
/// <param name="strsplit">分割字符串</param>
    
/// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
    
/// <returns>判断结果</returns>
    public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
    {
        
return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
    }
    
/// <summary>
    
/// 写js函数时用到,单字节换成又字节,以免出错
    
/// </summary>
    
/// <param name="theString">字符串</param>
    
/// <returns>返回双字节的字符串</returns>
    public static string singleToDouble(string theString)
    {
        theString 
= theString.Replace(",""");
        theString 
= theString.Replace("'""");
        
return theString;
    }
    
/// <summary>
    
/// 双变单
    
/// </summary>
    
/// <param name="theString"></param>
    
/// <returns></returns>
    public static string doubleToSingle(string theString)
    {
        theString 
= theString.Replace(""",");
        
return theString;
    }
    
/// <summary>
    
/// 取字符串长度
    
/// </summary>
    
/// <param name="Text"></param>
    
/// <returns></returns>
    public static int getStrLen(string Text)
    {
        
int len = 0;

        
for (int i = 0; i < Text.Length; i++)
        {
            
byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i, 1));
            
if (byte_len.Length > 1)
                len 
+= 2;  //如果长度大于1,是中文,占两个字节,+2
            else
                len 
+= 1;  //如果长度等于1,是英文,占一个字节,+1
        }

        
return len;
    }
    
#region 判断字符串是否为整型
    
/// <summary>
    
/// 判断字符串是否为整型
    
/// </summary>
    
/// <param name="s"></param>
    
/// <returns></returns>
    public static bool IsInt(string s)
    {
        
int i;
        
for (i = 0; i < s.Length; i++)
        {
            
char c;
            c 
= Convert.ToChar(s.Substring(i, 1));

            
if (!(c >= 0 && c <= 9))
            {
                
break;
            }
        }
        
if (i == s.Length)
        {
            
return true;
        }
        
else
        {
            
return false;
        }
    }
    
#endregion
    
#region 判断字符串是否为整型
    
/// <summary>
    
/// 判断字符串是否为整型
    
/// </summary>
    
/// <param name="s"></param>
    
/// <returns></returns>
    public static bool IsNumber(string s)
    {
        
int Flag = 0;
        
char[] str = s.ToCharArray();
        
for (int i = 0; i < str.Length; i++)
        {
            
if (Char.IsNumber(str[i]))
            {
                Flag
++;
            }
            
else
            {
                Flag 
= -1;
                
break;
            }
        }
        
if (Flag > 0)
        {
            
return true;
        }
        
else
        {
            
return false;
        }
    }
    
#endregion

posted on 2012-09-16 10:58 ** 阅读(681) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

公告

你好!

常用链接

留言簿(2)

随笔档案

文章分类

文章档案

新闻档案

相册

收藏夹

C#学习

友情链接

搜索

最新评论

阅读排行榜

评论排行榜