欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 常用公共方法

程序员文章站 2023-08-29 22:34:45
c# 常用公共方法,具体内容如下 1.后台调用weburl string hosturl = "http://www.a.com?id=123" ;...

c# 常用公共方法,具体内容如下

1.后台调用weburl

string hosturl = "http://www.a.com?id=123" ;
httpwebrequest myreq = (httpwebrequest)webrequest.create(hosturl);
myreq.method = "get";

httpwebresponse httpwresp = (httpwebresponse)myreq.getresponse();
stream mystream = httpwresp.getresponsestream();
streamreader sr = new streamreader(mystream, encoding.utf8);
stringbuilder strbuilder = new stringbuilder();
while (-1 != sr.peek())
{
strbuilder.append(sr.readline());
}
sr.close();
mystream.close();
httpwresp.close();

newtonsoft.json.linq.jobject jo = (newtonsoft.json.linq.jobject)newtonsoft.json.jsonconvert.deserializeobject(strbuilder.tostring());
string rescode = jo["returncode"].tostring();

2.检测输入url是否合法 

/// <summary>
 /// 判断网址是否可以访问
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 protected bool chkpageurl(string url)
 {
  bool result = false;
  try
  {
   httpwebrequest myhttpwebrequest = (httpwebrequest)webrequest.create(url);
   myhttpwebrequest.useragent = "mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko";
   myhttpwebrequest.method = "get";
   httpwebresponse myhttpwebresponse = (httpwebresponse)myhttpwebrequest.getresponse();
   if (myhttpwebresponse.statuscode == httpstatuscode.ok)
   {
    result = true;
   }
   myhttpwebresponse.close();
  }
  catch
  {
   result = false;
  }

  return result;
 }

3.批量导出

 /// <summary>
  /// 批量导出
  /// </summary>
  /// <returns></returns>
  public fileresult exportstu()
  {
   //创建excel文件的对象
   npoi.hssf.usermodel.hssfworkbook book = new npoi.hssf.usermodel.hssfworkbook();
   //添加一个sheet
   npoi.ss.usermodel.isheet sheet1 = book.createsheet("sheet1");
   int pager_totalcount = (int)session["pager_totalcount"];
   int totalcount = 0;
   //获取list数据
   list<articleentity> infolist = new achievedal.mytestdal().getarticlelist("", pager_totalcount, 1, out totalcount);

   //给sheet1添加第一行的头部标题
   npoi.ss.usermodel.irow row1 = sheet1.createrow(0);
   //创建时间 名称 商户订单号 | 交易号 对方 金额(元) 状态
   row1.createcell(0).setcellvalue("编号");
   row1.createcell(1).setcellvalue("标题");
   row1.createcell(2).setcellvalue("内容");
   int width = 256;
   sheet1.setcolumnwidth(0, 10 * width);
   sheet1.setcolumnwidth(1, 25 * width);
   sheet1.setcolumnwidth(2, 60 * width);
   if (infolist != null)
   {
    var list = infolist.orderbydescending(p => p.id);

    if (list != null)
    {
     int i = 0;
     //将数据逐步写入sheet1各个行
     foreach (var item in list)
     {
      i = i + 1;
      npoi.ss.usermodel.irow rowtemp = sheet1.createrow(i);
      rowtemp.createcell(0).setcellvalue(item.id.tostring());
      rowtemp.createcell(1).setcellvalue(item.title == null ? "" : item.title.tostring());
      rowtemp.createcell(2).setcellvalue(item.content == null ? "" : item.content.tostring());
     }
    }
   }
   // 写入到客户端 
   system.io.memorystream ms = new system.io.memorystream();
   book.write(ms);
   ms.seek(0, system.io.seekorigin.begin);
   return file(ms, "application/vnd.ms-excel", httputility.urlencode("导出", encoding.utf8).tostring() + datetime.now.tostring("yyyymmddhhmmss") + ".xls");

  }

4.批量导入 

 <input name="file" type="file" id="file" />
<input type="submit" name="upload" value="上传" />

/// <summary>
  /// 批量导入
  /// </summary>
  /// <returns></returns>
  [httppost]
  public actionresult importstu()
  {
   httppostedfilebase file = request.files["file"];
   string filename;
   string savepath;
   if (file == null || file.contentlength <= 0)
   {
    return content("<script>alert('上传失败,请选择上传文件!');location.href='/mytest/mvcpager';</script>");
   }
   else
   {
    string filename = path.getfilename(file.filename);
    int filesize = file.contentlength;//获取上传文件的大小单位为字节byte
    string fileex = system.io.path.getextension(filename);//获取上传文件的扩展名
    string nofilename = system.io.path.getfilenamewithoutextension(filename);//获取无扩展名的文件名
    string filetype = ".xls,.xlsx";//定义上传文件的类型字符串
    if (filetype.contains(".exe"))//excel
    {
     return content("<script>alert('上传文件类型格式错误,不允许导入exe格式的文件!');location.href='/mytest/mvcpager';</script>");
    }
    filename = nofilename + datetime.now.tostring("yyyymmddhhmmss") + fileex;
    string path = appdomain.currentdomain.basedirectory + "uploads/";
    savepath = path.combine(path, filename);
    file.saveas(savepath);

    if (filetype.contains(fileex))//excel
    {
     string strconn = "provider=microsoft.jet.oledb.4.0;data source=" + savepath + ";" + "extended properties=excel 8.0";
     oledbconnection conn = new oledbconnection(strconn);
     conn.open();
     oledbdataadapter mycommand = new oledbdataadapter("select * from [sheet1$]", strconn);
     dataset mydataset = new dataset();
     try
     {
      mycommand.fill(mydataset, "excelinfo");
     }
     catch (exception ex)
     {
      return content("<script>alert('上传失败," + ex.message + "!');location.href='/mytest/mvcpager';</script>");
     }
     //列顺序 标题 内容
     datatable table = mydataset.tables["excelinfo"].defaultview.totable();

     //事物 异常回滚
     using (transactionscope transaction = new transactionscope())
     {
      for (int i = 0; i < table.rows.count; i++)
      {
       articleentity model = new articleentity();
       model.title = table.rows[i][0].tostring();
       model.content = table.rows[i][1].tostring();
       new achievedal.mytestdal().addarticle(model);
      }
      transaction.complete();
     }
    }

    return redirecttoaction("mvcpager", "mytest");
   }
  }

5.获取客户端的ip地址 

/// <summary>
  /// 获取客户端的ip地址
  /// </summary>
  /// <returns>客户端ip地址</returns>
  public static string get_clientip()
  {
   string result = string.empty;
   result = httpcontext.current.request.headers["x-real-ip"]; //nginx 为前端时获取ip地址的方法
   if (result != null)
    return result;

   if (httpcontext.current.request.servervariables["remote_addr"] != null)//发出请求的远程主机的ip地址
   {
    result = httpcontext.current.request.servervariables["remote_addr"].tostring();
   }
   else if (httpcontext.current.request.servervariables["http_via"] != null)//判断是否设置代理,若使用了代理
   {
    if (httpcontext.current.request.servervariables["http_x_forwarded_for"] != null)//获取代理服务器的ip
    {
     result = httpcontext.current.request.servervariables["http_x_forwarded_for"].tostring();
    }
    else
    {
     result = httpcontext.current.request.userhostaddress;
    }
   }
   else
   {
    result = httpcontext.current.request.userhostaddress;
   }
   if (result == "::1")
    result = string.empty;
   return result;
  }

6.aes对称加密 

 /// <summary>
 /// 对称加密类
 /// </summary>
 public class aes
 {
  /// <summary>
  /// 解密
  /// </summary>
  /// <param name="strdecrypt"></param>
  /// <param name="strkey"></param>
  /// <returns></returns>
  public static string decrypt(string strdecrypt, string strkey)
  {
   try
   {
    byte[] bytes = encoding.utf8.getbytes(formsauthentication.hashpasswordforstoringinconfigfile(strkey, "md5"));
    byte[] inputbuffer = convert.frombase64string(strdecrypt);
    byte[] buffer3 = null;
    using (rijndaelmanaged managed = new rijndaelmanaged())
    {
     managed.key = bytes;
     managed.mode = ciphermode.ecb;
     managed.padding = paddingmode.pkcs7;
     buffer3 = managed.createdecryptor().transformfinalblock(inputbuffer, 0, inputbuffer.length);
    }
    return encoding.utf8.getstring(buffer3);
   }
   catch
   {
    return null;
   }
  }

  /// <summary>
  /// 解密
  /// </summary>
  /// <param name="strdecrypt"></param>
  /// <param name="strkey"></param>
  /// <returns></returns>
  public static string decrypt(string todecrypt, string key, string iv)
  {
   byte[] bytes = encoding.utf8.getbytes(key);
   byte[] buffer2 = encoding.utf8.getbytes(iv);
   byte[] inputbuffer = convert.frombase64string(todecrypt);
   rijndaelmanaged managed = new rijndaelmanaged
   {
    key = bytes,
    iv = buffer2,
    mode = ciphermode.cbc,
    padding = paddingmode.zeros
   };
   byte[] buffer4 = managed.createdecryptor().transformfinalblock(inputbuffer, 0, inputbuffer.length);
   return encoding.utf8.getstring(buffer4);
  }

  public static string decryptstr(string encryptstring)
  {
   string str = "";
   if (!string.isnullorempty(encryptstring))
   {
    string ssource = decrypt(encryptstring, "cn.solefu");
    if (utility.left(ssource, 3) == "gk_")
    {
     str = ssource.substring(3);
    }
   }
   return str;
  }

  public static string decryptstrbycbc(string encryptstring)
  {
   string str = "";
   if (!string.isnullorempty(encryptstring))
   {
    string ssource = decrypt(encryptstring, "cn.solefu", "cn.solefu");
    if (utility.left(ssource, 3) == "gk_")
    {
     str = ssource.substring(3);
    }
   }
   return str;
  }

  /// <summary>
  /// 加密
  /// </summary>
  /// <param name="strencrypt"></param>
  /// <param name="strkey"></param>
  /// <returns></returns>
  public static string encrypt(string strencrypt, string strkey)
  {
   try
   {
    byte[] bytes = encoding.utf8.getbytes(formsauthentication.hashpasswordforstoringinconfigfile(strkey, "md5"));
    byte[] inputbuffer = encoding.utf8.getbytes(strencrypt);
    byte[] inarray = null;
    using (rijndaelmanaged managed = new rijndaelmanaged())
    {
     managed.key = bytes;
     managed.mode = ciphermode.ecb;
     managed.padding = paddingmode.pkcs7;
     inarray = managed.createencryptor().transformfinalblock(inputbuffer, 0, inputbuffer.length);
    }
    return convert.tobase64string(inarray, 0, inarray.length);
   }
   catch
   {
    return null;
   }
  }

  /// <summary>
  /// 加密
  /// </summary>
  /// <param name="strencrypt"></param>
  /// <param name="strkey"></param>
  /// <returns></returns>
  public static string encrypt(string toencrypt, string key, string iv)
  {
   byte[] bytes = encoding.utf8.getbytes(key);
   byte[] buffer2 = encoding.utf8.getbytes(iv);
   byte[] inputbuffer = encoding.utf8.getbytes(toencrypt);
   rijndaelmanaged managed = new rijndaelmanaged
   {
    key = bytes,
    iv = buffer2,
    mode = ciphermode.cbc,
    padding = paddingmode.zeros
   };
   byte[] inarray = managed.createencryptor().transformfinalblock(inputbuffer, 0, inputbuffer.length);
   return convert.tobase64string(inarray, 0, inarray.length);
  }

  public static string encryptstr(string sourcestring)
  {
   return encrypt("gk_" + sourcestring, "cn.solefu");
  }

  public static string encryptstr(string sourcestring, bool useinurl)
  {
   return httputility.urlencode(encryptstr(sourcestring));
  }

  public static string encryptstrbycbc(string sourcestring)
  {
   return encrypt("gk_" + sourcestring, "cn.solefu", "cn.solefu");
  }

  public static string encryptstrbycbc(string sourcestring, bool useinurl)
  {
   return httputility.urlencode(encryptstrbycbc(sourcestring));
  }
 }

7.cookies帮助类 

public class cookieshelper
 {
  public static void addcookie(string cookiename, datetime expires)
  {
   httpcookie cookie = new httpcookie(cookiename)
   {
    expires = expires
   };
   addcookie(cookie, null);
  }

  public static void addcookie(string key, string value)
  {
   addcookie(new httpcookie(key, value), null);
  }

  public static void addcookie(httpcookie cookie, string domain)
  {
   httpresponse response = httpcontext.current.response;
   if (response != null)
   {
    cookie.httponly = true;
    cookie.path = "/";
    if (!string.isnullorempty(domain))
    {
     cookie.domain = domain;
    }
    response.appendcookie(cookie);
   }
  }

  public static void addcookie(string cookiename, datetime expires, string domain)
  {
   httpcookie cookie = new httpcookie(cookiename)
   {
    expires = expires
   };
   addcookie(cookie, domain);
  }

  public static void addcookie(string key, string value, datetime expires)
  {
   httpcookie cookie = new httpcookie(key, value)
   {
    expires = expires
   };
   addcookie(cookie, null);
  }

  public static void addcookie(string cookiename, string key, string value)
  {
   httpcookie cookie = new httpcookie(cookiename);
   cookie.values.add(key, value);
   addcookie(cookie, null);
  }

  public static void addcookie(string key, string value, bool withdomain, string domain)
  {
   if (withdomain)
   {
    addcookie(new httpcookie(key, value), domain);
   }
   else
   {
    addcookie(new httpcookie(key, value), null);
   }
  }

  public static void addcookie(string key, string value, datetime expires, string domain)
  {
   httpcookie cookie = new httpcookie(key, value)
   {
    expires = expires
   };
   addcookie(cookie, domain);
  }

  public static void addcookie(string cookiename, string key, string value, datetime expires)
  {
   httpcookie cookie = new httpcookie(cookiename)
   {
    expires = expires
   };
   cookie.values.add(key, value);
   addcookie(cookie, null);
  }

  public static void addcookie(string cookiename, string key, string value, string domain)
  {
   httpcookie cookie = new httpcookie(cookiename);
   cookie.values.add(key, value);
   addcookie(cookie, domain);
  }

  public static void addcookie(string cookiename, string key, string value, datetime expires, string domain)
  {
   httpcookie cookie = new httpcookie(cookiename)
   {
    expires = expires
   };
   cookie.values.add(key, value);
   addcookie(cookie, domain);
  }

  public static void adddomaincookie(string key, string value, string domain)
  {
   addcookie(new httpcookie(key, value), domain);
  }

  public static httpcookie getcookie(string cookiename)
  {
   httprequest request = httpcontext.current.request;
   if (request != null)
   {
    if (request.cookies[cookiename] != null)
    {
     return request.cookies[cookiename];
    }
    if (request.cookies[", " + cookiename] != null)
    {
     return request.cookies[", " + cookiename];
    }
   }
   return null;
  }

  public static string getcookievalue(string cookiename)
  {
   return getcookievalue(cookiename, null);
  }

  public static string getcookievalue(string cookiename, string key)
  {
   httprequest request = httpcontext.current.request;
   if (request == null)
   {
    return "";
   }
   if (request.cookies[cookiename] != null)
   {
    if (!string.isnullorempty(key) && request.cookies[cookiename].haskeys)
    {
     return request.cookies[cookiename].values[key];
    }
    return request.cookies[cookiename].value;
   }
   string str = ", " + cookiename;
   if (request.cookies[str] == null)
   {
    return "";
   }
   if (!string.isnullorempty(key) && request.cookies[str].haskeys)
   {
    return request.cookies[str].values[key];
   }
   return request.cookies[str].value;
  }

  public static string getcookievalue(httpcookie cookie, string key)
  {
   if (cookie == null)
   {
    return "";
   }
   if (!string.isnullorempty(key) && cookie.haskeys)
   {
    return cookie.values[key];
   }
   return cookie.value;
  }

  public static void removecookie(string cookiename)
  {
   removecookie(cookiename, null);
  }

  public static void removecookie(string cookiename, string key)
  {
   httpresponse response = httpcontext.current.response;
   if (response != null)
   {
    httpcookie cookie = response.cookies[cookiename];
    if (cookie != null)
    {
     if (!string.isnullorempty(key) && cookie.haskeys)
     {
      cookie.values.remove(key);
     }
     else
     {
      response.cookies.remove(cookiename);
     }
    }
   }
  }

  public static void setcookie(string cookiename, datetime expires)
  {
   setcookie(cookiename, null, null, new datetime?(expires), null);
  }

  public static void setcookie(string key, string value)
  {
   setcookie(key, null, value, null, null);
  }

  public static void setcookie(string cookiename, datetime expires, string domain)
  {
   setcookie(cookiename, null, null, new datetime?(expires), domain);
  }

  public static void setcookie(string key, string value, datetime expires)
  {
   setcookie(key, null, value, new datetime?(expires), null);
  }

  public static void setcookie(string cookiename, string key, string value)
  {
   setcookie(cookiename, key, value, null, null);
  }

  public static void setcookie(string key, string value, bool withdomain, string domain)
  {
   if (withdomain)
   {
    setcookie(key, null, value, null, domain);
   }
   else
   {
    setcookie(key, null, value, null, null);
   }
  }

  public static void setcookie(string key, string value, datetime expires, string domain)
  {
   setcookie(key, null, value, new datetime?(expires), domain);
  }

  public static void setcookie(string cookiename, string key, string value, string domain)
  {
   setcookie(cookiename, key, value, null, domain);
  }

  public static void setcookie(string cookiename, string key, string value, datetime? expires, string domain)
  {
   httpresponse response = httpcontext.current.response;
   if (response != null)
   {
    httpcookie cookie = response.cookies[cookiename];
    if (cookie != null)
    {
     cookie.path = "/";
     if (!string.isnullorempty(domain))
     {
      cookie.domain = domain;
     }
     if (!string.isnullorempty(key) && cookie.haskeys)
     {
      cookie.values.set(key, value);
     }
     else if (!string.isnullorempty(value))
     {
      cookie.value = value;
     }
     if (expires.hasvalue)
     {
      cookie.expires = expires.value;
     }
     response.setcookie(cookie);
    }
   }
  }
  /// <summary>
  /// 设置域的cookie
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  /// <param name="domain"></param>
  public static void setdomaincookie(string key, string value, string domain)
  {
   setcookie(key, null, value, null, domain);
  }
 }

8.datatable转换成实体类

 /// <summary>
 /// #region datatable转换成实体类
 /// </summary>
 /// <typeparam name="t"></typeparam>
 public class modelutil<t> where t : new()
 {

  /// <summary>
  /// 填充对象列表:用dataset的第一个表填充实体类
  /// </summary>
  /// <param name="ds">dataset</param>
  /// <returns></returns>
  public static list<t> fillmodel(dataset ds)
  {
   if (ds == null || ds.tables[0] == null || ds.tables[0].rows.count == 0)
   {
    return null;
   }
   else
   {
    return fillmodel(ds.tables[0]);
   }
  }

  /// <summary> 
  /// 填充对象列表:用dataset的第index个表填充实体类
  /// </summary> 
  public static list<t> fillmodel(dataset ds, int index)
  {
   if (ds == null || ds.tables.count <= index || ds.tables[index].rows.count == 0)
   {
    return null;
   }
   else
   {
    return fillmodel(ds.tables[index]);
   }
  }

  /// <summary> 
  /// 填充对象列表:用datatable填充实体类
  /// </summary> 
  public static list<t> fillmodel(datatable dt)
  {
   if (dt == null || dt.rows.count == 0)
   {
    return null;
   }
   list<t> modellist = new list<t>();
   foreach (datarow dr in dt.rows)
   {
    //t model = (t)activator.createinstance(typeof(t)); 
    t model = new t();
    for (int i = 0; i < dr.table.columns.count; i++)
    {
     list<propertyinfo> propertyinfos = model.gettype().getproperties().tolist();

     propertyinfo item = propertyinfos.firstordefault(p => string.compare(p.name, dr.table.columns[i].columnname, true) == 0);
     if (item != null && dr[i] != dbnull.value)
      try
      {
       item.setvalue(model, dr[i], null);
      }
      catch
      {
      }
    }

    modellist.add(model);
   }
   return modellist;
  }

  /// <summary> 
  /// 填充对象:用datarow填充实体类
  /// </summary> 
  public static t fillmodel(datarow dr)
  {
   if (dr == null)
   {
    return default(t);
   }

   //t model = (t)activator.createinstance(typeof(t)); 
   t model = new t();

   for (int i = 0; i < dr.table.columns.count; i++)
   {
    list<propertyinfo> propertyinfos = model.gettype().getproperties().tolist();

    propertyinfo item = propertyinfos.firstordefault(p => string.compare(p.name, dr.table.columns[i].columnname, true) == 0);
    if (item != null && dr[i] != dbnull.value)
     try
     {
      item.setvalue(model, dr[i], null);
     }
     catch
     {
     }
   }
   return model;
  }


  /// <summary>
  /// 实体类转换成dataset
  /// </summary>
  /// <param name="modellist">实体类列表</param>
  /// <returns></returns>
  public static dataset filldataset(list<t> modellist)
  {
   if (modellist == null || modellist.count == 0)
   {
    return null;
   }
   else
   {
    dataset ds = new dataset();
    ds.tables.add(filldatatable(modellist));
    return ds;
   }
  }

  /// <summary>
  /// 实体类转换成datatable
  /// </summary>
  /// <param name="modellist">实体类列表</param>
  /// <returns></returns>
  public static datatable filldatatable(list<t> modellist)
  {
   if (modellist == null || modellist.count == 0)
   {
    return null;
   }
   datatable dt = createdata(modellist[0]);

   foreach (t model in modellist)
   {
    datarow datarow = dt.newrow();
    foreach (propertyinfo propertyinfo in typeof(t).getproperties())
    {
     datarow[propertyinfo.name] = propertyinfo.getvalue(model, null);
    }
    dt.rows.add(datarow);
   }
   return dt;
  }

  /// <summary>
  /// 根据实体类得到表结构
  /// </summary>
  /// <param name="model">实体类</param>
  /// <returns></returns>
  private static datatable createdata(t model)
  {
   datatable datatable = new datatable(typeof(t).name);
   foreach (propertyinfo propertyinfo in typeof(t).getproperties())
   {
    datatable.columns.add(new datacolumn(propertyinfo.name, propertyinfo.propertytype));
   }
   return datatable;
  }

  /// <summary>
  /// 将datatable以转为list与dictionary嵌套集合保存
  /// </summary>
  /// <param name="dt"></param>
  /// <returns></returns>
  public static list<dictionary<string, string>> tolistdictionary(datatable dt)
  {
   list<dictionary<string, string>> list = null;
   if (dt != null && dt.rows.count > 0)
   {
    list = new list<dictionary<string, string>>();
    dictionary<string, string> dic = null;
    foreach (datarow dr in dt.rows)
    {
     dic = new dictionary<string, string>();
     foreach (datacolumn dc in dt.columns)
     {
      dic.add(dc.columnname, dr[dc.columnname].tostring());
     }
     list.add(dic);
    }
   }
   return list;
  }

  /// <summary>
  /// 请求的request的内容转换为model
  /// cza
  /// 2016-5-30 19:06:21
  /// </summary>
  /// <param name="context"></param>
  /// <returns></returns>
  public static t converttomodel(httpcontext context)
  {
   t t = new t();
   propertyinfo[] propertys = t.gettype().getproperties();
   foreach (propertyinfo pi in propertys)
   {
    if (!pi.canwrite)
     continue;
    object value = context.request[pi.name];
    if (value != null && value != dbnull.value)
    {
     try
     {
      if (value.tostring() != "")
       pi.setvalue(t, convert.changetype(value, pi.propertytype), null);//这一步很重要,用于类型转换
      else
       pi.setvalue(t, value, null);
     }
     catch
     { }
    }
   }

   return t;
  }


 }

9.sql server数据库访问类 

 /// <summary>
 /// sql server数据库访问类
 /// </summary>
 public abstract class sqlhelper
 {
  //读取配置文件里的数据库连接字符串
  public static readonly string connstr = configurationmanager.connectionstrings["conn"].connectionstring;

  //空构造
  public sqlhelper() { }

  //hashtable to store cached parameters
  private static hashtable parmcache = hashtable.synchronized(new hashtable());

  /// <summary>
  /// 执行增删改【常用】
  /// </summary>
  public static int executenonquery(string connectionstring, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   using (sqlconnection conn = new sqlconnection(connectionstring))
   {
    preparecommand(cmd, conn, null, commandtype, commandtext, paras);
    int val = cmd.executenonquery();
    cmd.parameters.clear();   //清空参数
    return val;
   }
  }

  /// <summary>
  /// 执行增删改(对现有的数据库连接)【不常用】
  /// </summary>
  public static int executenonquery(sqlconnection connection, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   preparecommand(cmd, connection, null, commandtype, commandtext, paras);
   int val = cmd.executenonquery();
   cmd.parameters.clear();
   return val;
  }

  /// <summary>
  /// 执行多条sql语句(list泛型集合)【事务】(无参数)
  /// </summary>
  /// <param name="connectionstring">数据库连接字符串</param>
  /// <param name="listsql">包含多条sql语句的泛型集合</param>
  /// <returns>受影响行数</returns>
  public static int executenonquery(string connectionstring, list<string> listsql)
  {
   sqlcommand cmd = new sqlcommand();
   sqlconnection conn = new sqlconnection(connectionstring);
   conn.open();
   sqltransaction trans = conn.begintransaction();
   preparecommand(cmd, conn, trans, commandtype.text, null, null);
   try
   {
    int count = 0;
    for (int n = 0; n < listsql.count; n++)
    {
     string strsql = listsql[n];
     if (strsql.trim().length > 1)
     {
      cmd.commandtext = strsql;
      count += cmd.executenonquery();
     }
    }
    trans.commit();
    cmd.parameters.clear();
    return count;
   }
   catch
   {
    trans.rollback();
    cmd.parameters.clear();
    return 0;
   }
   finally
   {
    conn.close();
   }
  }

  /// <summary>
  /// 执行多条sql语句(hashtable)【事务】(带一组参数,一个参数也得封装成组)
  /// </summary>
  /// <param name="connectionstring">数据库连接字符串</param>
  /// <param name="sqlstringlist">hashtable表,键值对形式</param>
  public static void executenonquery(string connectionstring, hashtable sqlstringlist)
  {
   using (sqlconnection conn = new sqlconnection(connectionstring))
   {
    conn.open();
    using (sqltransaction trans = conn.begintransaction())
    {
     sqlcommand cmd = new sqlcommand();
     try
     {
      foreach (dictionaryentry item in sqlstringlist)
      {
       string cmdtext = item.key.tostring(); //要执行的sql语句
       sqlparameter[] cmdparas = (sqlparameter[])item.value; //sql语句对应的参数
       preparecommand(cmd, conn, trans, commandtype.text, cmdtext, cmdparas);
       int val = cmd.executenonquery();
       cmd.parameters.clear();
      }
      if (sqlstringlist.count > 0)
       trans.commit();
     }
     catch
     {
      trans.rollback();
      throw;
     }
    }
   }

  }

  /// <summary>
  /// 返回datareader对象
  /// </summary>
  public static sqldatareader executereader(string connectionstring, commandtype commandtype, string cmdtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   sqlconnection conn = new sqlconnection(connectionstring);
   try
   {
    preparecommand(cmd, conn, null, commandtype, cmdtext, paras);
    sqldatareader reader = cmd.executereader(commandbehavior.closeconnection);
    cmd.parameters.clear();
    return reader;
   }
   catch
   {
    conn.close();
    throw;
   }
  }

  /// <summary>
  /// 返回第一行第一列信息(可能是字符串 所以返回类型是object)【常用】
  /// </summary>
  public static object executescalar(string connectionstring, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   using (sqlconnection connection = new sqlconnection(connectionstring))
   {
    preparecommand(cmd, connection, null, commandtype, commandtext, paras);
    object val = cmd.executescalar();
    cmd.parameters.clear();
    return val;
   }
  }

  /// <summary>
  /// 返回第一行第一列信息(针对现有的数据库连接)【不常用】
  /// </summary>
  public static object executescalar(sqlconnection connection, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();

   preparecommand(cmd, connection, null, commandtype, commandtext, paras);
   object val = cmd.executescalar();
   cmd.parameters.clear();
   return val;
  }

  /// <summary>
  /// 返回datatable
  /// </summary>
  public static datatable getdatatable(string connectionstring, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   using (sqlconnection conn = new sqlconnection(connectionstring))
   {
    preparecommand(cmd, conn, null, commandtype, commandtext, paras);
    using (sqldataadapter da = new sqldataadapter(cmd))
    {
     datatable dt = new datatable();
     da.fill(dt);
     return dt;
    }
   }
  }

  /// <summary>
  /// 返回dataset
  /// </summary>
  public static dataset getdataset(string connectionstring, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   sqlcommand cmd = new sqlcommand();
   using (sqlconnection conn = new sqlconnection(connectionstring))
   {
    preparecommand(cmd, conn, null, commandtype, commandtext, paras);
    using (sqldataadapter da = new sqldataadapter(cmd))
    {
     dataset ds = new dataset();
     da.fill(ds);
     return ds;
    }
   }
  }

  /// <summary>
  /// add parameter array to the cache
  /// </summary>
  /// <param name="cachekey">key to the parameter cache</param>
  /// <param name="cmdparms">an array of sqlparamters to be cached</param>
  public static void cacheparameters(string cachekey, params sqlparameter[] commandparameters)
  {
   parmcache[cachekey] = commandparameters;
  }

  /// <summary>
  /// retrieve cached parameters
  /// </summary>
  /// <param name="cachekey">key used to lookup parameters</param>
  /// <returns>cached sqlparamters array</returns>
  public static sqlparameter[] getcachedparameters(string cachekey)
  {
   sqlparameter[] cachedparms = (sqlparameter[])parmcache[cachekey];

   if (cachedparms == null)
    return null;

   sqlparameter[] clonedparms = new sqlparameter[cachedparms.length];

   for (int i = 0, j = cachedparms.length; i < j; i++)
    clonedparms[i] = (sqlparameter)((icloneable)cachedparms[i]).clone();

   return clonedparms;
  }

  /// <summary>
  /// 准备一个待执行的sqlcommand
  /// </summary>
  private static void preparecommand(sqlcommand cmd, sqlconnection conn, sqltransaction trans, commandtype commandtype, string commandtext, params sqlparameter[] paras)
  {
   try
   {
    if (conn.state != connectionstate.open)
    {
     conn.close();
     conn.open();
    }
    cmd.connection = conn;
    if (commandtext != null)
     cmd.commandtext = commandtext;
    cmd.commandtype = commandtype;  //这里设置执行的是t-sql语句还是存储过程

    if (trans != null)
     cmd.transaction = trans;

    if (paras != null && paras.length > 0)
    {
     //cmd.parameters.addrange(paras);
     for (int i = 0; i < paras.length; i++)
     {
      if (paras[i].value == null || paras[i].value.tostring() == "")
       paras[i].value = dbnull.value; //插入或修改时,如果有参数是空字符串,那么以null的形式插入数据库
      cmd.parameters.add(paras[i]);
     }
    }
   }
   catch (exception ex)
   {
    throw new exception(ex.message);
   }
  }

  /// <summary>
  /// 通用分页存储过程,有条件查询,有排序字段,按照排序字段的降序排列
  /// </summary>
  /// <param name="pagesize">每页记录数</param>
  /// <param name="currentcount">当前记录数量(页码*每页记录数)</param>
  /// <param name="tablename">表名称</param>
  /// <param name="where">查询条件,例:"id>1000 and name like '%lilinfeng%'" 排序条件,直接在后面加,例:" order by id desc,name asc"</param>
  /// <param name="totalcount">记录总数</param>
  /// <returns></returns>
  public static dataset getlist(string connectionstring, string order, int pagesize, int currentcount, string tablename, string where, out int totalcount)
  {
   sqlparameter[] parmlist =
    {
     new sqlparameter("@pagesize",pagesize),
     new sqlparameter("@currentcount",currentcount),
     new sqlparameter("@tablename",tablename),
     new sqlparameter("@where",where),
     new sqlparameter("@order",order),
     new sqlparameter("@totalcount",sqldbtype.int,4)
    };
   parmlist[5].direction = parameterdirection.output;
   dataset ds = getdataset(connectionstring, commandtype.storedprocedure, "sp_mvcpager", parmlist);
   totalcount = convert.toint32(parmlist[5].value);
   return ds;
  }
 }

10.日志文件记录 

 public class writelog
 {
  /// <summary>
  /// 
  /// </summary>
  /// <param name="filename">文件名</param>
  /// <param name="ex"></param>
  public static void writeerorrlog(string filename, exception ex)
  {
   if (ex == null) return; //ex = null 返回 
   datetime dt = datetime.now; // 设置日志时间 
   string time = dt.tostring("yyyy-mm-dd hh:mm:ss"); //年-月-日 时:分:秒 
   string logname = dt.tostring("yyyy-mm-dd"); //日志名称 
   string logpath = path.combine(system.appdomain.currentdomain.basedirectory, path.combine("log", filename)); //日志存放路径 
   string log = path.combine(logpath, string.format("{0}.log", logname)); //路径 + 名称
   try
   {
    fileinfo info = new fileinfo(log);
    if (info.directory != null && !info.directory.exists)
    {
     info.directory.create();
    }
    using (streamwriter write = new streamwriter(log, true, encoding.getencoding("utf-8")))
    {
     write.writeline(time);
     write.writeline(ex.message);
     write.writeline("异常信息:" + ex);
     write.writeline("异常堆栈:" + ex.stacktrace);
     write.writeline("异常简述:" + ex.message);
     write.writeline("\r\n----------------------------------\r\n");
     write.flush();
     write.close();
     write.dispose();
    }
   }
   catch { }
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="filename">文件名</param>
  /// <param name="message"></param>
  public static void writemessage(string filename, string message)
  {
   //ex = null 返回 
   datetime dt = datetime.now; // 设置日志时间 
   string time = dt.tostring("yyyy-mm-dd hh:mm:ss"); //年-月-日 时:分:秒 
   string logname = dt.tostring("yyyy-mm-dd"); //日志名称 
   string logpath = path.combine(system.appdomain.currentdomain.basedirectory, path.combine("log", filename)); //日志存放路径 
   string log = path.combine(logpath, string.format("{0}.log", logname)); //路径 + 名称
   try
   {
    fileinfo info = new fileinfo(log);
    if (info.directory != null && !info.directory.exists)
    {
     info.directory.create();
    }
    using (streamwriter write = new streamwriter(log, true, encoding.getencoding("utf-8")))
    {
     write.writeline(time);
     write.writeline("信息:" + message);
     write.writeline("\r\n----------------------------------\r\n");
     write.flush();
     write.close();
     write.dispose();
    }
   }
   catch { }
  }


  public static void writeerorrlog(exception ex, string message)
  {
   if (ex == null) return; //ex = null 返回 
   datetime dt = datetime.now; // 设置日志时间 
   string time = dt.tostring("yyyy-mm-dd hh:mm:ss"); //年-月-日 时:分:秒 
   string logname = dt.tostring("yyyy-mm-dd"); //日志名称 
   string logpath = system.appdomain.currentdomain.basedirectory; //日志存放路径 
   string log = path.combine(path.combine(logpath, "log"), string.format("{0}.log", logname)); //路径 + 名称
   try
   {
    fileinfo info = new fileinfo(log);
    if (info.directory != null && !info.directory.exists)
    {
     info.directory.create();
    }
    using (streamwriter write = new streamwriter(log, true, encoding.getencoding("utf-8")))
    {
     write.writeline(time);
     write.writeline(ex.message);
     write.writeline("异常信息:" + ex);
     write.writeline("异常堆栈:" + ex.stacktrace);
     write.writeline("异常简述:" + message);
     write.writeline("\r\n----------------------------------\r\n");
     write.flush();
     write.close();
     write.dispose();
    }
   }
   catch { }
  }

  public static void writemessage(string message)
  {
   //ex = null 返回 
   datetime dt = datetime.now; // 设置日志时间 
   string time = dt.tostring("yyyy-mm-dd hh:mm:ss"); //年-月-日 时:分:秒 
   string logname = dt.tostring("yyyy-mm-dd"); //日志名称 
   string logpath = system.appdomain.currentdomain.basedirectory; //日志存放路径 
   string log = path.combine(path.combine(logpath, "log"), string.format("{0}.log", logname)); //路径 + 名称
   try
   {
    fileinfo info = new fileinfo(log);
    if (info.directory != null && !info.directory.exists)
    {
     info.directory.create();
    }
    using (streamwriter write = new streamwriter(log, true, encoding.getencoding("utf-8")))
    {
     write.writeline(time);
     write.writeline("信息:" + message);
     write.writeline("\r\n----------------------------------\r\n");
     write.flush();
     write.close();
     write.dispose();
    }
   }
   catch { }
  }
 }

11.json帮助类 

 /// <summary>
 /// json帮助类
 /// </summary>
 public class jsonhelper
 {
  #region 通用方法
  /// <summary>
  /// 格式化字符型、日期型、布尔型
  /// </summary>
  public static string stringformat(string str, type type)
  {
   if (type == typeof(string))
   {
    str = stringfilter(str);
    str = "\"" + str + "\"";
   }
   else if (type == typeof(datetime) || type == typeof(datetime?))
   {
    str = "\"" + str + "\"";
   }
   else if (type == typeof(bool))
   {
    str = str.tolower();
   }
   else if (type == typeof(guid))
   {
    str = "\"" + str + "\"";
   }
   else if (type != typeof(string) && string.isnullorempty(str))
   {
    str = "\"" + str + "\"";
   }
   return str;
  }

  /// <summary>
  /// 过滤字符串
  /// </summary>
  public static string stringfilter(string str)
  {
   stringbuilder sb = new stringbuilder();
   for (int i = 0; i < str.length; i++)
   {
    char c = str.tochararray()[i];
    switch (c)
    {
     case '\"':
      sb.append("\\\""); break;
     case '\\':
      sb.append("\\\\"); break;
     case '/':
      sb.append("\\/"); break;
     case '\b':
      sb.append("\\b"); break;
     case '\f':
      sb.append("\\f"); break;
     case '\n':
      sb.append("\\n"); break;
     case '\r':
      sb.append("\\r"); break;
     case '\t':
      sb.append("\\t"); break;
     default:
      sb.append(c); break;
    }
   }
   return sb.tostring();
  }
  #endregion

  #region 列转json
  /// <summary>
  /// 列转json
  /// </summary>
  /// <param name="dt">表</param>
  /// <param name="r">列</param>
  public static string columntojson(datatable dt, int r)
  {
   stringbuilder strsql = new stringbuilder();
   for (int i = 0; i < dt.rows.count; i++)
   {
    strsql.append(dt.rows[i][r]);
    strsql.append(",");
   }
   return strsql.tostring().trim(',');
  }
  #endregion

  #region 对象转json
  /// <summary>
  /// 对象转json
  /// </summary>
  public static string tojson(object jsonobject)
  {
   stringbuilder sb = new stringbuilder();
   sb.append("{");
   propertyinfo[] propertyinfo = jsonobject.gettype().getproperties();
   for (int i = 0; i < propertyinfo.length; i++)
   {
    object objectvalue = propertyinfo[i].getgetmethod().invoke(jsonobject, null);
    type type = propertyinfo[i].propertytype;
    string strvalue = objectvalue.tostring();
    strvalue = stringformat(strvalue, type);
    sb.append("\"" + propertyinfo[i].name + "\":");
    sb.append(strvalue + ",");
   }
   sb.remove(sb.length - 1, 1);
   sb.append("}");
   return sb.tostring();
  }
  #endregion

  #region list转json
  /// <summary>
  /// list转json
  /// </summary>
  public static string listtojson<t>(ilist<t> list)
  {
   object obj = list[0];
   return listtojson<t>(list, obj.gettype().name);
  }

  private static string listtojson<t>(ilist<t> list, string jsonname)
  {
   stringbuilder json = new stringbuilder();
   if (string.isnullorempty(jsonname))
    jsonname = list[0].gettype().name;
   json.append("{\"" + jsonname + "\":[");
   if (list.count > 0)
   {
    for (int i = 0; i < list.count; i++)
    {
     t obj = activator.createinstance<t>();
     propertyinfo[] pi = obj.gettype().getproperties();
     json.append("{");
     for (int j = 0; j < pi.length; j++)
     {
      type type = pi[j].getvalue(list[i], null).gettype();
      json.append("\"" + pi[j].name.tostring() + "\":" + stringformat(pi[j].getvalue(list[i], null).tostring(), type));
      if (j < pi.length - 1)
      {
       json.append(",");
      }
     }
     json.append("}");
     if (i < list.count - 1)
     {
      json.append(",");
     }
    }
   }
   json.append("]}");
   return json.tostring();
  }
  #endregion

  #region 对象集合转换为json
  /// <summary>
  /// 对象集合转换为json
  /// </summary>
  /// <param name="array">对象集合</param>
  /// <returns>json字符串</returns>
  public static string tojson(ienumerable array)
  {
   string jsonstring = "[";
   foreach (object item in array)
   {
    jsonstring += tojson(item) + ",";
   }
   jsonstring = jsonstring.substring(0, jsonstring.length - 1);
   return jsonstring + "]";
  }
  #endregion

  #region 普通集合转换json
  /// <summary> 
  /// 普通集合转换json 
  /// </summary> 
  /// <param name="array">集合对象</param> 
  /// <returns>json字符串</returns> 
  public static string toarraystring(ienumerable array)
  {
   string jsonstring = "[";
   foreach (object item in array)
   {
    jsonstring = tojson(item.tostring()) + ",";
   }
   jsonstring.remove(jsonstring.length - 1, jsonstring.length);
   return jsonstring + "]";
  }
  #endregion

  #region dataset转换为json
  /// <summary> 
  /// dataset转换为json 
  /// </summary> 
  /// <param name="dataset">dataset对象</param> 
  /// <returns>json字符串</returns> 
  public static string tojson(dataset dataset)
  {
   string jsonstring = "{";
   foreach (datatable table in dataset.tables)
   {
    jsonstring += "\"" + table.tablename + "\":" + tojson(table) + ",";
   }
   jsonstring = jsonstring.trimend(',');
   return jsonstring + "}";
  }
  #endregion

  #region datatable转换为json
  /// <summary>  
  /// datatable转换为json  
  /// </summary> 
  public static string tojson(datatable dt)
  {
   if (dt.rows.count > 0)
   {
    stringbuilder jsonstring = new stringbuilder();
    jsonstring.append("[");
    datarowcollection drc = dt.rows;
    for (int i = 0; i < drc.count; i++)
    {
     jsonstring.append("{");
     for (int j = 0; j < dt.columns.count; j++)
     {
      string strkey = dt.columns[j].columnname;
      string strvalue = drc[i][j].tostring();

      type type = dt.columns[j].datatype;
      jsonstring.append("\"" + strkey + "\":");
      strvalue = stringformat(strvalue, type);
      if (j < dt.columns.count - 1)
       jsonstring.append(strvalue + ",");
      else
       jsonstring.append(strvalue);
     }
     jsonstring.append("},");
    }
    jsonstring.remove(jsonstring.length - 1, 1);
    jsonstring.append("]");
    return jsonstring.tostring();
   }
   else
    return "[]";
  }

  /// <summary> 
  /// datatable转换为json
  /// </summary> 
  public static string tojson(datatable dt, string jsonname)
  {
   stringbuilder json = new stringbuilder();
   if (string.isnullorempty(jsonname))
    jsonname = dt.tablename;
   json.append("{\"" + jsonname + "\":[");
   if (dt.rows.count > 0)
   {
    for (int i = 0; i < dt.rows.count; i++)
    {
     json.append("{");
     for (int j = 0; j < dt.columns.count; j++)
     {
      type type = dt.rows[i][j].gettype();
      json.append("\"" + dt.columns[j].columnname.tostring() + "\":" + stringformat(dt.rows[i][j].tostring(), type));
      if (j < dt.columns.count - 1)
       json.append(",");
     }
     json.append("}");
     if (i < dt.rows.count - 1)
      json.append(",");
    }
   }
   json.append("]}");
   return json.tostring();
  }
  #endregion

  #region datareader转换为json
  /// <summary>  
  /// datareader转换为json  
  /// </summary>  
  /// <param name="datareader">datareader对象</param>  
  /// <returns>json字符串</returns> 
  public static string tojson(dbdatareader datareader)
  {
   stringbuilder jsonstring = new stringbuilder();
   jsonstring.append("[");
   while (datareader.read())
   {
    jsonstring.append("{");
    for (int i = 0; i < datareader.fieldcount; i++)
    {
     type type = datareader.getfieldtype(i);
     string strkey = datareader.getname(i);
     string strvalue = datareader[i].tostring();
     jsonstring.append("\"" + strkey + "\":");
     strvalue = stringformat(strvalue, type);
     if (i < datareader.fieldcount - 1)
      jsonstring.append(strvalue + ",");
     else
      jsonstring.append(strvalue);
    }
    jsonstring.append("},");
   }
   datareader.close();
   jsonstring.remove(jsonstring.length - 1, 1);
   jsonstring.append("]");
   return jsonstring.tostring();
  }
  #endregion


  #region 返回错误
  public static string error()
  {
   datatable dt = new datatable();
   dt.columns.add("error", typeof(int));
   datarow dr = dt.newrow();
   dr["error"] = 1;
   dt.rows.add(dr);
   return tojson(dt);
  }
  #endregion

 }


11.转换帮助类
 


 public class converthelper
 {
  public static int datetimetounixint(datetime time)
  {
   datetime time2 = timezone.currenttimezone.tolocaltime(new datetime(0x7b2, 1, 1));
   timespan span = (timespan)(time - time2);
   return (int)span.totalseconds;
  }

  public static decimal moneyround(decimal value, int decimals)
  {
   if (value < 0m)
   {
    return math.round((decimal)(value + (5m / ((decimal)math.pow(10.0, (double)(decimals + 1))))), decimals, midpointrounding.awayfromzero);
   }
   return math.round(value, decimals, midpointrounding.awayfromzero);
  }

  public static double moneyround(double value, int decimals)
  {
   if (value < 0.0)
   {
    return math.round((double)(value + (5.0 / math.pow(10.0, (double)(decimals + 1)))), decimals, midpointrounding.awayfromzero);
   }
   return math.round(value, decimals, midpointrounding.awayfromzero);
  }

  public static decimal moneytodecimal(string str)
  {
   try
   {
    str = str.replace(",", "");
    return decimal.parse(str);
   }
   catch
   {
    return 0m;
   }
  }

  public static decimal round(decimal d, int i)
  {
   if (d >= 0m)
   {
    d += 5m * ((decimal)math.pow(10.0, (double)-(i + 1)));
   }
   else
   {
    d += -5m * ((decimal)math.pow(10.0, (double)-(i + 1)));
   }
   string str = d.tostring();
   string[] strarray = str.split(new char[] { '.' });
   int index = str.indexof('.');
   string str2 = strarray[0];
   string str3 = strarray[1];
   if (str3.length > i)
   {
    str3 = str.substring(index + 1, i);
   }
   d = decimal.parse(str2 + "." + str3);
   return d;
  }

  public static double round(double d, int i)
  {
   if (d >= 0.0)
   {
    d += 5.0 * math.pow(10.0, (double)-(i + 1));
   }
   else
   {
    d += -5.0 * math.pow(10.0, (double)-(i + 1));
   }
   string str = d.tostring();
   string[] strarray = str.split(new char[] { '.' });
   int index = str.indexof('.');
   string str2 = strarray[0];
   string str3 = strarray[1];
   if (str3.length > i)
   {
    str3 = str.substring(index + 1, i);
   }
   d = double.parse(str2 + "." + str3);
   return d;
  }

  public static bool tobool(object o)
  {
   return tobool(o, false);
  }

  public static bool tobool(object o, bool defaultvalue)
  {
   bool flag;
   if (bool.tryparse(tostring(o, true), out flag))
   {
    return flag;
   }
   return defaultvalue;
  }

  public static datetime todatetime(object o)
  {
   return todatetime(o, datetime.now);
  }

  public static datetime todatetime(object o, datetime defaultvalue)
  {
   datetime time;
   if (datetime.tryparse(tostring(o, true), out time))
   {
    return time;
   }
   return defaultvalue;
  }

  public static decimal todecimal(object o)
  {
   return todecimal(o, 0m);
  }

  public static decimal todecimal(object o, decimal defaultvalue)
  {
   decimal num;
   if (decimal.tryparse(tostring(o, true), out num))
   {
    return num;
   }
   return defaultvalue;
  }

  public static double todouble(object o)
  {
   return todouble(o, 0.0);
  }

  public static double todouble(object o, double defaultvalue)
  {
   double num;
   if (double.tryparse(tostring(o, true), out num))
   {
    return num;
   }
   return defaultvalue;
  }

  public static float tofloat(object o)
  {
   return tofloat(o, 0f);
  }

  public static float tofloat(object o, float defaultvalue)
  {
   float num;
   if (float.tryparse(tostring(o, true), out num))
   {
    return num;
   }
   return defaultvalue;
  }

  public static int toint(object o)
  {
   return toint(o, 0);
  }

  public static int toint(object o, int defaultvalue)
  {
   int num;
   if (int.tryparse(tostring(o, true), out num))
   {
    return num;
   }
   return defaultvalue;
  }

  public static long tolong(object o)
  {
   return tolong(o, 0l);
  }

  public static long tolong(object o, long defaultvalue)
  {
   long num;
   if (long.tryparse(tostring(o, true), out num))
   {
    return num;
   }
   return defaultvalue;
  }

  public static string tomoney(object o)
  {
   return todecimal(o).tostring("###,###,###,###,###,##0.##");
  }

  public static string tomoney(string str)
  {
   try
   {
    return decimal.parse(str).tostring("###,###,###,###,###,##0.##");
   }
   catch
   {
    return "0";
   }
  }

  public static string tostring(object o)
  {
   return tostring(o, "", false);
  }

  public static string tostring(object o, bool btrim)
  {
   return tostring(o, "", btrim);
  }

  public static string tostring(object o, string defaultvalue)
  {
   return tostring(o, defaultvalue, false);
  }

  public static string tostring(object o, string defaultvalue, bool btrim)
  {
   if (object.equals(o, null) || convert.isdbnull(o))
   {
    return defaultvalue;
   }
   if (btrim)
   {
    return o.tostring().trim();
   }
   return o.tostring();
  }

  public static datetime unixinttodatetime(string timestamp)
  {
   datetime time = timezone.currenttimezone.tolocaltime(new datetime(0x7b2, 1, 1));
   long ticks = long.parse(timestamp + "0000000");
   timespan span = new timespan(ticks);
   return time.add(span);
  }
 } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。