C#常见操作类(二)
1、生成缩略图
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ProjectCommon
{
public class ImageCLass
{
#region 生成缩略图
/// <summary>
/// 根据大图找到缩略图路径
/// </summary>
/// <param name="imgPath">大图路径</param>
/// <returns></returns>
public static string GetSmallImg(string imgPath)
{
return imgPath.Substring(0, imgPath.LastIndexOf('.') - 2) + System.IO.Path.GetExtension(imgPath);
}
/// <summary>
/// 根据大图生成缩略图
/// </summary>
/// <param name="savePath">原始图片路径</param>
/// <param name="picFilePath">原始图片</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
public static void GenSmallImg(string imgPath, int width, int height)
{
string smallPath = imgPath.Substring(0, imgPath.LastIndexOf('.')) + "s1" + System.IO.Path.GetExtension(imgPath);
System.Drawing.Image img = System.Drawing.Image.FromFile(imgPath);
Bitmap tempBitmap = new Bitmap(width, height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(tempBitmap);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);
g.DrawImage(img, rectDestination, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
KiSaveAsJPEG(tempBitmap, smallPath, 90);
if (img != null)
img.Dispose();
if (tempBitmap != null)
tempBitmap.Dispose();
}
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
}
/// <summary>
/// 保存为JPEG格式,支持压缩质量选项
/// </summary>
/// <param name="bmp"></param>
/// <param name="FileName"></param>
/// <param name="Qty"></param>
/// <returns></returns>
private static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
{
try
{
EncoderParameter p;
EncoderParameters ps;
ps = new EncoderParameters(1);
p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
ps.Param[0] = p;
bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);
return true;
}
catch
{
return false;
}
}
#endregion
/// <summary>
/// md5加密
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string md5(string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
string result = string.Empty;
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(source));
result = BitConverter.ToString(s).Replace("-", string.Empty);
return result.ToLower();
}
/// <summary>
/// 移除html标签
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string RemoveHtml(string html)
{
if (string.IsNullOrEmpty(html)) return html;
string result = "";
Regex regex = new Regex("<.+?>");
var matches = regex.Matches(html);
foreach (Match match in matches)
{
html = html.Replace(match.Value, "");
}
return result;
}
//将图片以二进制流
public byte[] SaveImage(String path)
{
if (!string.IsNullOrEmpty(path))
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
return imgBytesIn;
}
return null;
}
//现实二进制流代表的图片
public MemoryStream ShowImgByByte(byte[] imgBytesIn)
{
MemoryStream ms = new MemoryStream(imgBytesIn);
// pictureBox1.Image = Image.FromStream(ms);
return ms;
}
}
}
2、C#常用的方法
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace ProjectCommon
{
public static class MyExtensions
{
public static int[] SplitTOInt(this string strs, char ch)
{
string[] arrstr = strs.Split(ch);
int[] arrint = new int[arrstr.Length];
for (int i = 0; i < arrstr.Length; i++)
{
arrint[i] = int.Parse(arrstr[i].ToString());
}
return arrint;
}
public static List<string> SplitTOList(this string strs, char ch)
{
List<string> Lstr = new List<string>();
string[] arrstr = strs.Split(ch);
int[] arrint = new int[arrstr.Length];
for (int i = 0; i < arrstr.Length; i++)
{
Lstr.Add(arrstr[i].ToString());
}
return Lstr;
}
public static Dictionary<string, string> SplitTODictionary(this string strs, char ch, string strKey)
{
Dictionary<string, string> Lstr = new Dictionary<string, string>();
string[] arrstr = strs.Split(ch);
int[] arrint = new int[arrstr.Length];
for (int i = 0; i < arrstr.Length; i++)
{
Lstr.Add(arrstr[i].ToString(), strKey);
}
return Lstr;
}
/// <summary>
/// 将List转化为String
/// </summary>
/// <param name="Lists"></param>
/// <param name="ch"></param>
/// <returns></returns>
public static string ListTOString(this List<string> Lists, char ch)
{
string strReturn = "";
foreach (var item in Lists)
{
strReturn = strReturn + item.ToString() + ch;
}
return strReturn.TrimEnd(ch);
}
/// <summary>
/// 将List(int)转化为String
/// </summary>
/// <param name="Lists"></param>
/// <param name="ch"></param>
/// <returns></returns>
public static string ListTOString(this List<int> Lists, char ch)
{
string strReturn = "";
foreach (var item in Lists)
{
strReturn = strReturn + item.ToString() + ch;
}
return strReturn.TrimEnd(ch);
}
/// <summary>
/// 获取需要IN的格式
/// </summary>
/// <param name="strKys"></param>
/// <returns></returns>
public static string ToFormatLike(this string strKys)
{
StringBuilder sbKeys = new StringBuilder();
foreach (var item in strKys.Split(','))
{
sbKeys.AppendFormat("'" + item.ToString() + "',");
}
return sbKeys.Length > 0 ? sbKeys.ToString().TrimEnd(',').Trim('\'') : "";
}
/// <summary>
/// 取前N个字符,后面的用省略号代替
/// </summary>
/// <param name="strKys"></param>
/// <returns></returns>
public static string ToMangneStr(this string strKys, int intLenght)
{
return strKys.Length > intLenght ? strKys.Substring(0, intLenght) + "…………" : strKys;
}
public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
public static DataTable OrderBy(this DataTable dt, string orderBy)
{
dt.DefaultView.Sort = orderBy;
return dt.DefaultView.ToTable();
}
public static DataTable Where(this DataTable dt, string where)
{
DataTable resultDt = dt.Clone();
DataRow[] resultRows = dt.Select(where);
foreach (DataRow dr in resultRows) resultDt.Rows.Add(dr.ItemArray);
return resultDt;
}
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(this DataTable dt)
{
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);
if (jsonString.Length != 0)
{
jsonString.Append("]");
}
return jsonString.ToString();
}
public static string ToJson(this Object dataSource)
{
var st = new StringBuilder();
var jss = new JavaScriptSerializer();
jss.Serialize(dataSource, st);
return st.ToString();
}
public static int ToInt32(this Object obj)
{
return Convert.ToInt32(obj);
}
public static DateTime ToDateTime(this Object obj)
{
return Convert.ToDateTime(obj);
}
public static T GetProperty<T>(this object obj, string propertyName)
{
var property = obj.GetType().GetProperty(propertyName);
if (property != null)
{
return (T)property.GetValue(obj, null);
}
throw new ArgumentNullException(propertyName);
}
/// <summary>
/// DataTable转成Json
/// </summary>
/// <param name="jsonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(this 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();
}
/// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.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();
}
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
public static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(Int32))
{
if (str.Trim() == "")
{
str = "\"" + str + "\"";
}
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
return str;
}
/// <summary>
/// 过滤特殊字符
/// 如果字符串为空,直接返回。
/// </summary>
/// <param name="str">需要过滤的字符串</param>
/// <returns>过滤好的字符串</returns>
public static string FilterSpecial(this string str)
{
if (str == "")
{
return str;
}
else
{
str = str.Replace("'", "");
str = str.Replace("<", "");
str = str.Replace(">", "");
str = str.Replace("%", "");
str = str.Replace("'delete", "");
str = str.Replace("''", "");
str = str.Replace("\"\"", "");
str = str.Replace(",", "");
str = str.Replace(".", "");
str = str.Replace(">=", "");
str = str.Replace("=<", "");
str = str.Replace(";", "");
str = str.Replace("||", "");
str = str.Replace("[", "");
str = str.Replace("]", "");
str = str.Replace("&", "");
str = str.Replace("#", "");
str = str.Replace("/", "");
str = str.Replace("|", "");
str = str.Replace("?", "");
str = str.Replace(">?", "");
str = str.Replace("?<", "");
return str;
}
}
/// <summary>
/// 过滤特殊字符
/// 如果字符串为空,直接返回。
/// </summary>
/// <param name="str">需要过滤的字符串</param>
/// <returns>过滤好的字符串</returns>
public static string FilterSQL(this string str)
{
if (str == String.Empty)
return String.Empty;
str = str.Replace("'", "''");
string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
if ((str != null) && (str != String.Empty))
{
string str_Regex = @"\b(" + SqlStr + @")\b";
Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
string s = Regex.Match(str).Value;
if (!string.IsNullOrEmpty(s))
{
str = str.Replace(s, "");
}
}
return str;
}
/// <summary>
/// 根据条件过滤表
/// </summary>
/// <param name="dt">未过滤之前的表</param>
/// <param name="filter">过滤条件</param>
/// <returns>返回过滤后的表</returns>
public static DataTable FilterTable(this DataTable dt, string filter)
{
DataTable newTable = dt.Clone();
DataRow[] drs = dt.Select(filter);
foreach (DataRow dr in drs)
{
newTable.Rows.Add(dr.ItemArray);
}
return newTable;
}
public static DataTable SplitDataTable(this DataTable dt, int PageIndex, int PageSize)
{
if (PageIndex == 0)
return dt;
DataTable newdt = dt.Clone();
//newdt.Clear();
int rowbegin = (PageIndex - 1) * PageSize;
int rowend = PageIndex * PageSize;
if (rowbegin >= dt.Rows.Count)
return newdt;
if (rowend > dt.Rows.Count)
rowend = dt.Rows.Count;
for (int i = rowbegin; i <= rowend - 1; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
}
return newdt;
}
}
}
3、获取页面内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ProjectCommon
{
/// <summary>
/// 公共方法类
/// </summary>
public class WebHandler
{
/// <summary>
/// 获取网页的HTML码
/// </summary>
/// <param name="url">链接地址</param>
/// <param name="encoding">编码类型</param>
/// <returns></returns>
public static string GetHtmlStr(string url, string encoding)
{
string htmlStr = "";
try
{
if (!String.IsNullOrEmpty(url))
{
WebRequest request = WebRequest.Create(url); //实例化WebRequest对象
WebResponse response = request.GetResponse(); //创建WebResponse对象
Stream datastream = response.GetResponseStream(); //创建流对象
Encoding ec = Encoding.Default;
if (encoding == "UTF8")
{
ec = Encoding.UTF8;
}
else if (encoding == "Default")
{
ec = Encoding.Default;
}
StreamReader reader = new StreamReader(datastream, ec);
htmlStr = reader.ReadToEnd(); //读取网页内容
reader.Close();
datastream.Close();
response.Close();
}
}
catch { }
return htmlStr;
}
}
}
4、消息返回类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectCommon
{
/// <summary>
/// 返回消息类
/// </summary>
public class Msg_Result
{
public string Action { get; set; }
public string ErrorMsg { get; set; }
public int DataLength { get; set; }
public string ResultType { get; set; }
public dynamic Result { get; set; }
public dynamic Result1 { get; set; }
public dynamic Result2 { get; set; }
public dynamic Result3 { get; set; }
public dynamic Result4 { get; set; }
public dynamic Result5 { get; set; }
}
}