C#帮助类库整理

C#帮助类库整理

文章目录

    • C#帮助类库整理
      • 1.日志记录帮助类库
      • 2. Json操作帮助类库
      • 3.下载网页源代码帮助类
      • 4.读取程序中的appSettings.json文件

1.日志记录帮助类库

根据Log4net封装:

 public class LogHelper
    {
        static LogHelper()
        {
             //通过Nuget添加Log4net的引用
            XmlConfigurator.Configure(new Uri(AppDomain.CurrentDomain.BaseDirectory+@"ConfigFiles/log4net.cfg.xml"));
            ILog log = LogManager.GetLogger(typeof(LogHelper));
            log.Info("系统初始化Logger模块");
        }

        private ILog logger = null;

        public LogHelper(Type type)
        {
            logger = LogManager.GetLogger(type);
        }

        public void Error(string msg="出現異常",Exception ex=null)
        {
            Console.WriteLine(msg);
            logger.Error(msg,ex);
        }

        public void Warn(string msg)
        {
            Console.WriteLine(msg);
            logger.Warn(msg);
        }

        public void Info(string msg)
        {
            Console.WriteLine(msg);
            logger.Info(msg);
        }

        public void Debug(string msg)
        {
            Console.WriteLine(msg);
            logger.Debug(msg);
        }

    }


  
  
    

    
    

    
    

    
    
    

    
    

    
    
    
    

    
    

    
    

    
    
      
      
    

    
      
    
  

  
  
    
    
    
  

2. Json操作帮助类库

 public class JsonHelper
    {
        /// 
        /// 读取json文件
        /// 
        /// 
        /// 
        public static string ReadJson(string filePath)
        {
            return File.ReadAllText(filePath);
        }

        /// 
        /// 利用newtonsoft.json序列化
        /// 
        /// 
        /// 
        /// 
        public static string NewtonsoftSerialiize(T t)
        {
            return JsonConvert.SerializeObject(t);
        }

        /// 
        ///  利用newtonsoft.json反序列化
        /// 
        /// 
        /// 
        /// 
        public static T NewtonsoftDeserialize(string content)
        {
            return JsonConvert.DeserializeObject (content);
        }
    }

3.下载网页源代码帮助类

(1)HttpRequest

 public class HttpHelper
    {
        public static string DownLoadHtmlByUrl(string url)
        {
            return DownLoadHtml(url,Encoding.UTF8);
        }


        public static string DownLoadHtml(string url, Encoding encode)
        {
            string html = string.Empty;
            try
            {
                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
                request.Timeout = 30 * 1000;//设置30s超时
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0";//模拟浏览器信息
                request.ContentType = "text/html; charset=utf-8";
                request.CookieContainer = new CookieContainer();
                using (HttpWebResponse response =request.GetResponse() as HttpWebResponse)//发起请求
                {
                    if(response.StatusCode!=HttpStatusCode.OK)
                    {

                    }
                    else
                    {
                        try
                        {
                            using (StreamReader read = new StreamReader(response.GetResponseStream(), encode))
                            {
                                html = read.ReadToEnd();//读取数据
                                read.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            html = null;
                            throw;
                        }
                    }
                }

            }
            catch (System.Net.WebException ex)
            {

                if (ex.Message.Equals("远程服务器返回错误: (306)。"))
                {
                   
                    html = null;
                }
            }
            catch (Exception ex)
            {
               
                html = null;
            }
            return html;
        }
    }


(2)HttpClient

 public class HttpClientHelper
    {
        public static string GetResponseByGet( string url)
        {
            string result = "";

            var httpclient = new HttpClient();

           
            var response = httpclient.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                result = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }

            return result;
        }
    }

4.读取程序中的appSettings.json文件

  /// 
    /// 固定读取根目录下appsettings.json
    /// 
    public class ConfigrationManager
    {
        //第一次使用时候初始化
        static ConfigrationManager()
        {
            var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json");

            IConfigurationRoot configuration = builder.Build();
            // _SqlConnectionString = configuration["connectionString"];
            _SqlConnectionString = configuration.GetConnectionString("SchoolContext");
        }

        #region 数据库连接
        private static string _SqlConnectionString = null;
        public static string SqlConnectionString
        {
            get
            {
                return _SqlConnectionString;
            }
        }
        #endregion

    }
{
  "ConnectionStrings": {
    "SchoolContext": "server=localhost;userid=root;pwd=123456;port=3306;database=mytest;sslmode=none;Convert Zero Datetime=True"
  }

}

你可能感兴趣的:(c#)