收集的C#常用类代码


//--方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;

/// <summary>
/// 表示Web上的通用方法,如顯示提示信息,獲取日期,錯誤日志維護等.
/// </summary>
public class WebCom
{
    public WebCom()
    {

    }
    /// <summary>
    /// 顯示javascript的alert消息框,彈出消息框
    /// </summary>
    /// <param name="orgPage"></param>
    /// <param name="strMessage"></param>
    public static void ShowJsMessage(Page orgPage, string strMessage)
    {
        Random random = new Random();
        string strKey = "__ShowMessage" + random.Next(10000).ToString() + "()";
        if (orgPage.ClientScript.IsStartupScriptRegistered(strKey))
        {
            strKey = "__ShowMessage" + random.Next(10000).ToString() + "()";
        }
        string strScript = "<script language=\"JavaScript\">\n\r" +
            "  alert(\"" + strMessage.Replace("\r", Convert.ToString(13)).Replace("\n", Convert.ToString(10))

            + "\")\n\r" + " </script>\n\r";
        Type csType = orgPage.GetType();
        orgPage.ClientScript.RegisterStartupScript(csType, strKey, strScript);
    }
    /// <summary>
    /// 顯示javascript的消息框,彈出消息框
    /// </summary>
    /// <param name="orgPage"></param>
    /// <param name="errorMessage"></param>
    /// <param name="messHeight"></param>
    /// <param name="messWidth"></param>
    public static void ShowJsMessage(Page orgPage, string errorMessage, int messHeight, int messWidth)
    {
        Random random = new Random();
        string strKey = "__ShowErrorMessage" + random.Next(10000).ToString() + "()";
        if (orgPage.ClientScript.IsStartupScriptRegistered(strKey))
        {
            strKey = "__ShowErrorMessage" + random.Next(10000).ToString() + "()";
        }
        string strScript = "<script language=\"JavaScript\">\n\r" +
            " $(document).ready(ShowErrorMessage);\n\r" +
            " function ShowErrorMessage() " +
            " {\n\r" +
            "   ShowMessageBox(\"" + errorMessage.Replace("\r", Convert.ToString(13)).Replace("\n", Convert.ToString(10))

            + "\"," + messWidth + "," + messHeight + ")\n\r" + "} \n\r</script>\n\r";
        Type csType = orgPage.GetType();
        orgPage.ClientScript.RegisterStartupScript(csType, strKey, strScript);

    }
    /// <summary>
    /// 給出系統提示信息
    /// </summary>
    /// <param name="vErrorMessage"></param>
    /// <returns></returns>
    public static string ShowSystemTip(string vErrorMessage)
    {
        StringBuilder ErrorMessage = new StringBuilder();
        ErrorMessage.Length = 0;
        ErrorMessage.Append("<div style=\"padding:20px;width:200px;height:150px\"><div class=\"x-box-blue\"><div class=\"x-box-tl\"><div class=\"x-box-tr\"><div class=\"x-box-tc\"></div></div></div>");
        ErrorMessage.Append("<div class=\"x-box-ml\"><div class=\"x-box-mr\"><div class=\"x-box-mc\">");
        ErrorMessage.Append("<h3>System Message</h3><div style='height:100px;text-align:center;vertical-align: middle;line-height:40px'><font color=#FF0000 size=4 nowrap>" + vErrorMessage + "</font></div>");
        ErrorMessage.Append(" </div></div></div>");
        ErrorMessage.Append(" <div class=\"x-box-bl\"><div class=\"x-box-br\">");
        ErrorMessage.Append(" <div class=\"x-box-bc\"></div></div></div>");
        ErrorMessage.Append(" </div></div>");
        return ErrorMessage.ToString();
    }
    /// <summary>
    /// 給出系統提示信息,並指定信息的接受者
    /// </summary>
    /// <param name="vTip"></param>
    /// <param name="vHeight"></param>
    /// <param name="vWidth"></param>
    /// <returns></returns>
    public static string ShowSystemTip(string vTip, int vHeight, int vWidth)
    {
        StringBuilder ErrorMessage = new StringBuilder();
        ErrorMessage.Length = 0;
        ErrorMessage.Append("  <div style='padding:20px;'><div style='width:" + vWidth + "px;' class='main-div'  > <div class='main-top-left'> <div class='main-top-right'><div class='main-top-header'>系統提示信息</div></div></div>");
        ErrorMessage.Append(" <div class='main-middle-left'><div class='main-middle-right'><div class='main-content-border'><div class='main-content' style='height:" + vHeight + "px;padding:5px;font-size:11pt;color:red'>");
        ErrorMessage.Append(vTip);
        ErrorMessage.Append("</div></div></div></div><div class='main-bottom-left'> <div class='main-bottom-right'><div class='main-bottom-middle'></div></div></div></div></div>");
        return ErrorMessage.ToString();
    }
    /// <summary>
    ///  加密字符,防止敏感信息外泄.
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string EncodeBase(string s)
    {
        string strResult = "";
        if (s != "" && s != null)
        {
            strResult = Convert.ToBase64String(System.Text.ASCIIEncoding.Default.GetBytes(s));
        }
        return strResult;
    }


    /// <summary>
    /// 解密字符,防止敏感信息外泄.
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string DecodeBase(string s)
    {
        string strResult = "";
        if (s != "" && s != null)
        {
            strResult = System.Text.ASCIIEncoding.Default.GetString(Convert.FromBase64String(s));
        }
        return strResult;
    }

    /// <summary>
    /// 根據周別來獲取本周日期的第一天
    /// </summary>
    /// <param name="weekID"></param>
    /// <returns></returns>
    public static string GetWeekFirstDay(string weekID)
    {
        int year = int.Parse(weekID.Substring(0, 4));
        DateTime newYearDay = new DateTime(year, 1, 1);
        int firstWeekFirstDay = Convert.ToInt32(newYearDay.DayOfWeek);
        int days = (int)(7 - firstWeekFirstDay);
        DateTime secondWeekFirstDay = newYearDay.AddDays(days);
        int week = int.Parse(weekID.Substring(4, 2));
        string firstDate = secondWeekFirstDay.AddDays((week - 2) * 7).ToString("yyyy-MM-dd");
        return firstDate;
    }

    /// <summary>
    /// 根據周別來獲取本周日期的最后一天
    /// </summary>
    /// <param name="weekID"></param>
    /// <returns></returns>
    public static string GetWeekLastDay(string weekID)
    {
        int year = int.Parse(weekID.Substring(0, 4));
        DateTime newYearDay = new DateTime(year, 1, 1);
        int firstweekfirstday = Convert.ToInt32(newYearDay.DayOfWeek);
        int days = (int)(7 - firstweekfirstday);
        DateTime secondweekfisrtday = newYearDay.AddDays(days);
        int week = int.Parse(weekID.Substring(4, 2));
        string lastdate = secondweekfisrtday.AddDays((week - 2) * 7 + 6).ToString("yyyy-MM-dd");
        return lastdate;
    }


    /// <summary>
    ///
    /// </summary>
    /// <param name="weekId"></param>
    /// <returns></returns>
    public static string[] GetWeekRange(string weekId)
    {
        string[] day = new string[7];
        int year = int.Parse(weekId.Substring(0, 4));
        DateTime newYearDay = new DateTime(year, 1, 1);
        int firstweekfirstday = Convert.ToInt32(newYearDay.DayOfWeek);
        int days = (int)(7 - firstweekfirstday);
        DateTime secondweekfisrtday = newYearDay.AddDays(days);
        int week = int.Parse(weekId.Substring(4, 2));
        DateTime firstdate = secondweekfisrtday.AddDays((week - 2) * 7);
        DateTime lastdate = secondweekfisrtday.AddDays((week - 2) * 7 + 6);
        day[0] = firstdate.ToString("yyyy-MM-dd");
        for (int i = 1; i <= 5; i++)
        {
            day[i] = firstdate.AddDays(i).ToString("yyyy-MM-dd");
        }
        day[6] = lastdate.ToString("yyyy-MM-dd");
        return day;
    }


    /// <summary>
    /// 根據日期返回周次
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string GetWeekOfYear(DateTime dt)
    {
        CultureInfo ci = CultureInfo.CurrentCulture;
        System.Globalization.Calendar calendar = ci.Calendar;
        CalendarWeekRule rule = ci.DateTimeFormat.CalendarWeekRule;
        DayOfWeek dow = ci.DateTimeFormat.FirstDayOfWeek;
        int week = calendar.GetWeekOfYear(dt, rule, dow);
        string weekId = dt.Year + week.ToString("00");
        return weekId;
    }
    /// <summary>
    /// 判斷是否輸入整數數字的正則表達
    /// </summary>
    /// <param name="Validate"></param>
    /// <returns></returns>
    public static bool CheckValidate(string Validate)
    {
        Regex re = new Regex(@"^[0-9]+$");//正則表達式

        if (!re.IsMatch(Validate))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    /// <summary>
    /// 產生隨機的字母
    /// </summary>
    /// <returns></returns>
    public static string RandomnAlpha(int i)
    {
        string oriStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstyuwxyz";
        string reStr = "";
        Random rd = new Random();
        for (int k = 0; k < i; k++)
        {
            reStr += oriStr[rd.Next(0, oriStr.Length)].ToString();
        }
        return reStr;
    }
    /// <summary>
    /// 將信息寫入日志文件中
    /// </summary>
    /// <param name="textContent">日志內容</param>
    /// <param name="Path">文件路徑</param>
    public static void WriteLog(string textContent, string Path)
    {
        if (!File.Exists(Path))
        {
            using (StreamWriter writer = File.CreateText(Path))
            {
                writer.WriteLine(textContent + "\n");
                writer.Close();
                //string LOG_SOURCE = ConfigurationManager.AppSettings["Event Log Source"];
                //System.Diagnostics.EventLog.WriteEntry(LOG_SOURCE, textContent, System.Diagnostics.EventLogEntryType.Error);

            }
        }
        else
        {
            using (StreamWriter writer2 = File.AppendText(Path))
            {
                try
                {
                    writer2.WriteLine(textContent + "\n");
                    writer2.Close();
                }
                catch
                {

                }
            }
        }
    }
    /// <summary>
    /// 字符截取擴展
    /// <para></para>
    /// <para> 解決C# 採用 Unicode 16(UCS2)編碼,對於漢字不能處理.</para>
    ///
    /// </summary>
    /// <param name="oriString"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    public static string SubStr(string oriString, int length)
    {
        byte[] bytes = System.Text.Encoding.Unicode.GetBytes(oriString);
        int n = 0; 
        int i = 0; 
        for (; i < bytes.GetLength(0) && n < length; i++)
        {
            if (i % 2 == 0)
            {
                n++;    
            }
            else
            {
                if (bytes[i] > 0)
                {
                    n++;
                }
            }
        }
        if (i % 2 == 1)
        {
            if (bytes[i] > 0)

                i = i - 1;
            else
                i = i + 1;
        }
        return System.Text.Encoding.Unicode.GetString(bytes, 0, i);

    }

}

posted @ 2010-07-21 22:58  你妹的sb  阅读(479)  评论(0编辑  收藏  举报
百度一下