c#工具包代码

我有一个习惯,学习一种新的语言,希望会有一种对应的工具包,这样开发效率会加快。C#刚学不久,目前构建了一个小工具包如下。工具包持续更新,放在KangryUtils包中。

Functions.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace KangryUtils
{
    class Functions
    {
        /*******************************************************************************************
         * 时间相关函数
         *******************************************************************************************/
        /// <summary>
        /// 验证日期是否正确
        /// </summary>
        /// <param name="year">年份,int类型</param>
        /// <param name="month">月份,int类型</param>
        /// <param name="day">日期,int类型</param>
        /// <returns>布尔值</returns>
        public static bool checkDate(int year, int month, int day)
        {
            try
            {
                DateTime.Parse(year + "-" + month + "-" + day);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 验证日期是否正确
        /// </summary>
        /// <param name="dateStr">表示日期的字符串</param>
        /// <returns>布尔值</returns>
        public static bool checkDate(string dateStr)
        {
            try
            {
                DateTime.Parse(dateStr);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
        /// <summary>  
        /// 获取当前时间戳(秒数)  
        /// </summary>   
        /// <returns></returns>  
        public static int getTimeStamp()
        {
            return getTimeStamp(DateTime.Now);
        }
        /// <summary>
        /// 获得特定的时间戳
        /// </summary>
        /// <param name="time">DateTime类型的时间</param>
        /// <returns></returns>
        public static int getTimeStamp(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return Convert.ToInt32((time - startTime).TotalSeconds);
        }
        /// <summary>
        /// 获得特定的时间戳
        /// </summary>
        /// <param name="time">字符串表示的时间</param>
        /// <returns>若时间字符串格式正确,则返回时间戳,否则返回-1</returns>
        public static int getTimeStamp(string time)
        {
            int timestamp=-1;
            try
            {
                DateTime dt = Convert.ToDateTime(time);
                timestamp = getTimeStamp(dt);
            }
            catch (Exception e)
            {
                Log.errorLog("Fail to convert to timeStamp from a string: " + time);
            }
            return timestamp;
        }
        /// <summary>
        /// 通过时间戳获得DateTime
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static DateTime getDateTime(int timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan ts = new TimeSpan(0, 0, timeStamp);
            return dtStart.Add(ts);
        }
        /// <summary>
        /// 获得DateTime
        /// </summary>
        /// <param name="time">字符串时间</param>
        /// <returns></returns>
        public static DateTime getDateTime(string time)
        {
            return getDateTime(getTimeStamp(time));
        }
        /// <summary>
        /// 转化时间格式
        /// </summary>
        /// <param name="sDt">原有的时间字符串</param>
        /// <param name="format">要转化的格式串</param>
        /// <returns>若成功,返回转换好的时间字符串,否则返回null</returns>
        public static string formatDateTime(string sDt, string format = "yyyy-MM-dd HH:mm:ss")
        {
            string sDateTime = null;
            try
            {
                sDateTime = formatDateTime(Convert.ToDateTime(sDt), format);
            }
            catch
            {
                Log.errorLog("Fail to convert the time string: " + sDt + " to a given format: " + format);
            }
            return null;
        }
        /// <summary>
        /// 转化时间格式
        /// </summary>
        /// <param name="sDt">原有的DateTime格式时间</param>
        /// <param name="format">要转化的格式串</param>
        /// <returns>若成功,返回转换好的时间字符串,否则返回null</returns>
        public static string formatDateTime(DateTime dt, string format = "yyyy-MM-dd HH:mm:ss")
        {
            string sDateTime=null;
            try
            {
                sDateTime = dt.ToString(format); 
            }
            catch (Exception e)
            {
                Log.errorLog("Fail to convert the time to a given format: " + format);
            }
            return sDateTime;
        }
        /// <summary>
        /// 通过时间戳获得特定格式的时间
        /// </summary>
        /// <param name="iTimeStamp"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string formatDateTime(int iTimeStamp, string format = "yyyy-MM-dd HH:mm:ss")
        {
            return formatDateTime(getDateTime(iTimeStamp), format);
        }

        /********************************************************************************************
         * 文件相关函数
         ********************************************************************************************/
        /// <summary>
        /// 创建文件夹路径
        /// </summary>
        /// <param name="filePath">文件夹路径</param>
        /// <returns>是否创建成功</returns>
        public static bool makeDir(string filePath)
        {
            bool flag = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
            if (!fi.Directory.Exists)
            {
                try
                {
                    fi.Directory.Create();
                }
                catch (Exception e)
                {
                    Log.traceLog("Fail to build directory: " + fi.Directory.ToString() + e.Message);    //此处不用错误日志是防止递归调用
                    flag = false;
                }
            }
            return flag;
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filePath">要创建的文件路径</param>
        /// <param name="append">是否往后追加</param>
        /// <returns>streamWriter</returns>
        public static StreamWriter makeFile(string filePath, bool append=true)
        {
            if(!makeDir(filePath))
            {
                return null;
            }
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(filePath, append);
            }
            catch (Exception e)
            {
                Log.traceLog("Fail to build a file: " + filePath + e.Message);    //此处不用错误日志是防止递归调用
            }
            return sw;
        }
    }
}

Log.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace KangryUtils
{
    class Log
    {
        //跟踪的日志
        public static void traceLog(string content, bool bWriteToFile = false, string logFile = "")
        {
            string formatDate = Functions.formatDateTime(DateTime.Now, "yyyy-MM-dd HH:mm:ss");
            TextWriterTraceListener fileT = null;
            StreamWriter sw = null;

            if (bWriteToFile)
            {
                if (logFile != "")
                {
                    sw = Functions.makeFile(logFile);
                }
                else
                {
                    string year = formatDate.Substring(0, 4);
                    string month = formatDate.Substring(5, 2);
                    string day = formatDate.Substring(8, 2);
                    sw = Functions.makeFile("traceLog/" + year + "/" + month + "/" + year + "-" + month + "-" + day + ".log");
                }
            }

            if (sw != null)
            {
                fileT = new TextWriterTraceListener(sw);
                Trace.Listeners.Add(fileT);
            }
            TextWriterTraceListener t = new TextWriterTraceListener(Console.Out);
            Trace.Listeners.Add(t);
            Trace.AutoFlush = true;
            Trace.WriteLine("[" + formatDate + "]");
            Trace.Indent();
            Trace.WriteLine(content, "Trace");
            Trace.Unindent();
            Trace.Listeners.Remove(t);
            if (sw != null)
            {
                Trace.Listeners.Remove(fileT);
                sw.Close();
            }
        }

        //错误日志,同时写入文件
        public static void errorLog(string content, bool bWriteToFile = true, string logFile = "")
        {
            string formatDate=Functions.formatDateTime(DateTime.Now, "yyyy-MM-dd HH:mm:ss");
            TextWriterTraceListener fileT=null;
            StreamWriter sw=null;

            if (bWriteToFile)
            {
                if (logFile != "")
                {
                    sw = Functions.makeFile(logFile);
                }
                else
                {
                    string year = formatDate.Substring(0, 4);
                    string month = formatDate.Substring(5, 2);
                    string day = formatDate.Substring(8, 2);
                    sw = Functions.makeFile("errorLog/" + year + "/" + month + "/" + year + "-" + month + "-" + day + ".log");
                }
            }
            
            if (sw != null)
            {
                fileT = new TextWriterTraceListener(sw);
                Trace.Listeners.Add(fileT);
            }
            TextWriterTraceListener t = new TextWriterTraceListener(Console.Out);
            Trace.Listeners.Add(t);
            Trace.AutoFlush = true;
            Trace.WriteLine("[" + formatDate + "]");
            Trace.Indent();
            Trace.WriteLine(content, "Error");
            Trace.Unindent();
            Trace.Listeners.Remove(t);
            if (sw != null)
            {
                Trace.Listeners.Remove(fileT);
                sw.Close();
            }
        }
    }
}

Db.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace KangryUtils
{
    class Db
    {
        private SqlConnection con;
        public Db()
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            try
            {
                con = new SqlConnection(ConnectionString);
            }
            catch (Exception e)
            {
                Log.errorLog("Fail to connect to database!\n" + e.Message);
            }
        }
        public Db(string connectionString)
        {
            try
            {
                con = new SqlConnection(connectionString);
            }
            catch (Exception e)
            {
                Log.errorLog("Fail to connect to database!\n" + e.Message);
            }
        }
        //关闭数据库
        public void Close()
        {
            if (con.State != ConnectionState.Closed)
            {
                try
                {
                    con.Close();
                }
                catch (Exception e)
                {
                    Log.errorLog("Fail to close database!\n" + e.Message); 
                }
            }
        }
        //属性,判断连接对象的状态并打开连接对象
        public SqlConnection Con
        {
            get
            {
                switch (con.State)
                {
                    case ConnectionState.Broken:
                        try
                        {
                            con.Close(); //先正常关闭,释放资源
                        }
                        catch(Exception e)
                        {
                            Log.errorLog("Fail to close database!\n"+e.Message);
                        }
                        try
                        {
                            con.Open();
                        }
                        catch(Exception e)
                        {
                            Log.errorLog("Fail to open database!\n"+e.Message);
                        }
                        break;
                    case ConnectionState.Closed:
                        try
                        {
                            con.Open();
                        }
                        catch(Exception e)
                        {
                            Log.errorLog("Fail to open database!\n"+e.Message);
                        }
                        break;
                    case ConnectionState.Connecting:
                    case ConnectionState.Executing:
                    case ConnectionState.Fetching:
                    case ConnectionState.Open:
                        break;
                    default:
                        break;
                }
                return con;
            }
            set { con = value; }
        }
    }
}

在用工具包之前,需要引入连个引用:system.web和system.web.extension;

转载请注明:康瑞部落 » c#工具包代码

0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注