常用方法
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace CMS.Common
{
public class StringPlus
{
private const string PASSWORD_BASE = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";
/// <summary>
/// 去除第一个字符,取出第一个字符之后的所有字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DeleteFirstChar(string str)
{
return str.Substring(1, str.Length - 1);
}
/// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(0, str.LastIndexOf(strchar));
}
/// <summary>
/// 截取指定字符长度
/// </summary>
/// <param name="str"></param>
/// <param name="strchar"></param>
/// <returns></returns>
public static string SubstringChar(string str, int length)
{
return str.Substring(0, length);
}
/// <summary>
/// 从指定、特殊字符开始截取
/// </summary>
/// <param name="str">http://192.168.1.41:8086/upload/customer/123456_20160315181634.jpg</param>
/// <param name="IndexOf">/upload</param>
/// <returns>/upload/customer/123456_20160315181634.jpg</returns>
public static string SubstringIndexOfChar(string str, string IndexOf)
{
//return str.Substring(str.IndexOf("/upload"));
return str.Substring(str.IndexOf(IndexOf) + 1);
}
/// <summary>
/// 去掉最後一個字符
/// </summary>
/// <param name="prestr"></param>
/// <returns></returns>
public static string DeleteLastChar(string prestr)
{
int nLen = prestr.Length;
return prestr.Remove(nLen - 1, 1);
}
#region 替换特殊字符,并让特殊字符的下一个字母为大写
/// <summary>
/// 替换特殊字符,并让特殊字符的下一个字母为大写
/// 调用方式:string abc = StringPlus.ReplaceUnderlineAndfirstToUpper("gmt_modify_yyyy_mmmm", "_");
/// </summary>
/// <param name="srcStr">原始字符串</param>
/// <param name="org">特殊字符</param>
/// <param name="ob"></param>
/// <returns></returns>
public static string ReplaceUnderlineAndfirstToUpper(string srcStr, string org)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(srcStr) && !string.IsNullOrEmpty(org))
{
string[] array = srcStr.Split(org);
foreach (var item in array)
{
result += item.Substring(0, 1).ToUpper() + item.Substring(1);
}
}
return result;
}
/// <summary>
/// 替换特殊字符,并让特殊字符的下一个字母为大写
/// 调用方式:string bb = StringPlus.ConvertToInitialPascal("gmt_modify_yyyy_mmmm");
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ConvertToInitialPascal(string str)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '_')
{
result += str[i + 1].ToString().ToUpper();
i++;
}
else
result += str[i].ToString().ToLower();
}
result = result.Substring(0, 1).ToUpper() + result.Substring(1);
}
return result;
}
#endregion
/// <summary>
/// 图片文件转Base64String
/// </summary>
/// <param name="FilePath">文件绝对路径</param>
/// <returns></returns>
public static string ImageToBase64(string FilePath)
{
string path = @"F:\5845.jpg";
return Convert.ToBase64String(System.IO.File.ReadAllBytes(path));
}
/**
* 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
* @return 时间戳
*/
public static string GenerateTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/**
* 生成随机串,随机串包含字母或数字
* @return 随机串
*/
public static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
/// <summary>
/// 随机密码
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string RandomPassword(int length)
{
StringBuilder sb = new StringBuilder();
Random rnd = new Random();
for (int i = 0; i < length; i++)
{
sb.Append(PASSWORD_BASE[rnd.Next(0, PASSWORD_BASE.Length)]);
}
return sb.ToString();
}
/// <summary>
/// 生成随机数
/// </summary>
/// <param name="length">生成字符串长度</param>
/// <param name="type">1.数字+字母 2.整形 3.字符 4.许愿墙随机坐标代码</param>
/// <returns></returns>
public static string GenerateCode(int length, int type)
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
if (type == 1)
{
for (int i = 0; i < length; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
}
else if (type == 2)
{
for (int i = 0; i < length; i++)
{
number = random.Next();
code = (char)('0' + (char)(number % 10));
checkCode += code.ToString();
}
}
else if (type == 3)
{
for (int i = 0; i < length; i++)
{
number = random.Next();
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
}
else if (type == 4)//许愿墙随机坐标代码
{
for (int i = 0; i < length; i++)
{
number = random.Next(10, 450);
checkCode = number.ToString();
}
}
return checkCode;
}
/// <summary>
/// 生成随机数
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string BuildRandomStr(int length)
{
Random rand = new Random();
int num = rand.Next();
string str = num.ToString();
if (str.Length > length)
{
str = str.Substring(0, length);
}
else if (str.Length < length)
{
int n = length - str.Length;
while (n > 0)
{
str.Insert(0, "0");
n--;
}
}
return str;
}
/// <summary>
/// 现有数组中抽取1个随机数
/// </summary>
/// <returns></returns>
public static string ArrayRandom(long[] arr)
{
string[] item = new string[4] { "1", "2", "3", "4" };
Random r = new Random();
string fi1 = arr[r.Next(arr.Length)].ToString();
return fi1;
}
/// <summary>
/// 把字符串进行URL编码
/// </summary>
/// <param name="src"></param>
/// <param name="code"></param>
/// <returns></returns>
public static string UrlEncodeCode(string src, Encoding code)
{
return HttpUtility.UrlEncode(src, code);
}
/// <summary>
/// 把字符串进行UTF8编码
/// </summary>
/// <param name="src"></param>
/// <returns></returns>
public static string UrlEncodeUTF8(string src)
{
return HttpUtility.UrlEncode(src, System.Text.Encoding.UTF8);
}
/// <summary>
/// 把字符串进行URL编码
/// </summary>
/// <param name="src">原字符串</param>
/// <param name="srcEncoding">Encoding.UTF8</param>
/// <returns></returns>
public static string UrlEncode(string src, System.Text.Encoding encoding)
{
byte[] b = encoding.GetBytes(src);
StringBuilder result = new StringBuilder();
for (int i = 0; i < b.Length; i++)
{
result.Append('%');
result.Append(b[i].ToString("X2"));
}
return result.ToString();
}
/// <summary>
/// Base64加密
/// </summary>
/// <param name="str">123456</param>
/// <param name="encoding">Encoding.UTF8</param>
/// <returns></returns>
public static string ToBase64String(string str, System.Text.Encoding encoding)
{
string encodeStr;
byte[] bytes = encoding.GetBytes(str);
encodeStr = Convert.ToBase64String(bytes);
return encodeStr;
}
/// <summary>
/// Base64加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToBase64String(string str)
{
return ToBase64String(str, Encoding.UTF8);
}
/// <summary>
/// Base64String转换成byte[]
/// </summary>
/// <param name="fileBase"></param>
/// <returns></returns>
public static byte[] Base64ToByte(string base64String)
{
byte[] file = null;
if (!string.IsNullOrEmpty(base64String))
{
file = Convert.FromBase64String(base64String);
}
return file;
}
/// <summary>
/// 带有“,”的字符串转成int[]
/// </summary>
/// <param name="str">1,2,3,4,5,6,8,9,10,</param>
/// <returns></returns>
public static int[] StringToIntArray(string str)
{
int[] intArray = null;
if (!string.IsNullOrEmpty(str))
{
string newStr = str.TrimEnd(',');
intArray = newStr.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
}
return intArray;
}
/// <summary>
/// int[]转成String字符串
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static string IntArrayToString(int[] array)
{
string result = string.Empty;
if (array.Count() > 0)
{
for (int i = 0; i < array.Length; i++)
{
if (0 == i)
{
result = array[0].ToString();
}
else
{
result = result + "," + array[i].ToString();
}
}
}
return result;
}
/// <summary>
/// int[]转成String字符串
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static string IntArrayToStringJoin(int[] array)
{
string result = string.Empty;
if (array.Count() > 0)
{
result = string.Join(",", array);
}
return result;
}
/// <summary>
/// 带有“,”的字符串转成string[]
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] StringToStrArray(string str)
{
string[] strArray = null;
if (!string.IsNullOrEmpty(str))
{
strArray = str.Split(',');
}
return strArray;
}
/// <summary>
/// 字符串数组转为 long[] 数组
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static long[] ConvertAllLong(string[] array)
{
long[] result = Array.ConvertAll<string, long>(array, s => long.Parse(s));
long[] result1 = Array.ConvertAll<int, long>(new int[] { 1, 2, 3 }, s => s);
string[] result2 = Array.ConvertAll<int, string>(new int[] { 1, 2, 3 }, s => Convert.ToString(s));
return result;
}
/// <summary>
/// Dictionary转成String[]数组
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] DictionaryToStrArray(Dictionary<string, string> dicArray)
{
string[] strArray = null;
if (dicArray.Count > 0)
{
List<string> list = new List<string>();
foreach (var item in dicArray)
{
list.Add(item.Value);
}
strArray = list.ToArray();
}
return strArray;
}
/// <summary>
/// 带有“,”的字符串转成Dictionary<string, string>
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Dictionary<string, string> StringToDictionary(string str)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(str))
{
string[] strArray = str.Split(',');
for (int i = 0; i < strArray.Length; i++)
{
string value = strArray[i].ToString();
if (StringPlus.SubstringChar(value, 4) != "http")
{
dict.Add("pic" + i.ToString(), value);
}
}
}
return dict;
}
/// <summary>
/// Dictionary转成String字符串
/// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
/// </summary>
/// <param name="dicArray">需要拼接的数组</param>
/// <returns>拼接完成以后的字符串</returns>
public static string DictionaryToString(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
if (dicArray.Count > 0)
{
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Key + "=" + temp.Value + "&");
}
//去掉最後一個&字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1);
}
return prestr.ToString();
}
/// <summary>
/// Dictionary转成Json字符串
/// </summary>
/// <param name="dicArray"></param>
/// <returns></returns>
public static string DictionaryToJson(Dictionary<string, string> dicArray)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("token", "123456789");
dict.Add("cookies", JsonConvert.DeserializeObject<JObject>("789456123"));//不会有“\”反斜杠,转义符
return JsonConvert.SerializeObject(dict);
}
/// <summary>
/// Dictionary转成Json
/// </summary>
/// <param name="dicArray"></param>
/// <returns></returns>
public static string DictToJson(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
prestr.Append("[");
if (dicArray.Count > 0)
{
int i = 0;
foreach (KeyValuePair<string, string> temp in dicArray)
{
if (i == 0)
{
prestr.Append("{\"" + temp.Key + "\":" + temp.Value + ",");
}
else if (i == dicArray.Count - 1)
{
prestr.Append("\"" + temp.Key + "\":" + temp.Value + "}");
}
else
{
prestr.Append("\"" + temp.Key + "\":" + temp.Value + ",");
}
i++;
}
}
prestr.Append("]");
return prestr.ToString();
}
/// <summary>
/// Dictionary转成String字符串
/// </summary>
/// <param name="dicList"></param>
/// <returns></returns>
private static String buildQueryStr(Dictionary<String, String> dicList)
{
String postStr = "";
foreach (var item in dicList)
{
postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
}
postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
return postStr;
}
/// <summary>
/// String[]转成String字符串
/// </summary>
/// <param name="arrParams"></param>
/// <returns></returns>
public static String buildParamStr(String[] arrParams)
{
String postStr = "";
for (int i = 0; i < arrParams.Length; i++)
{
if (0 == i)
{
postStr = "chatroomId=" + HttpUtility.UrlDecode(arrParams[0], Encoding.UTF8);
}
else
{
postStr = postStr + "&" + "chatroomId=" + HttpUtility.UrlEncode(arrParams[i], Encoding.UTF8);
}
}
return postStr;
}
/// <summary>
/// Guid[]转成String字符串
/// </summary>
/// <param name="arrParams"></param>
/// <returns></returns>
public static string ArrayToString(Guid[] arrParams)
{
string postStr = "";
for (int i = 0; i < arrParams.Length; i++)
{
if (0 == i)
{
postStr = "'" + arrParams[0].ToString() + "'";
}
else
{
postStr = postStr + "," + "'" + arrParams[i].ToString() + "'";
}
}
return postStr;
}
public static T GetNullToDefault<T>(T value)
{
try
{
if (value == null)
return default(T);
else
return (T)value;
}
catch (Exception)
{
return default(T);
}
///调用示例
//string test = GetNullToDefault("test");
//int count = GetNullToDefault<int>(123);
//decimal price = GetNullToDefault<decimal>(Convert.ToDecimal(123.45));
//decimal total = GetNullToDefault<decimal>(Convert.ToDecimal(null));
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static T GetNullValue<T>(T data)
{
if (data == null)
return default(T);
return (T)data;
///调用示例
//string test = GetNullValue("test");
//string str = GetNullValue<string>("test");
//int count = GetNullValue<int>(123);
//decimal price = GetNullValue<decimal>(Convert.ToDecimal(123.45));
//decimal total = GetNullValue<decimal>(Convert.ToDecimal(null));
}
/// <summary>
/// GetNullValue调用示例
/// </summary>
public void TestGetNullValue()
{
string str = GetNullValue<string>("test");
int count = GetNullValue<int>(123);
decimal price = GetNullValue<decimal>(Convert.ToDecimal(123.45));
decimal total = GetNullValue<decimal>(Convert.ToDecimal(null));
}
public static int GetNullToInt(int? id)
{
try
{
if (id == null)
return 0;
else
return (int)id;
}
catch (Exception)
{
return 0;
}
}
public static int GetStringToInt(string id)
{
try
{
if (string.IsNullOrEmpty(id))
return 0;
else
return Convert.ToInt32(id);
}
catch (Exception)
{
return 0;
}
}
public static long GetNullToLong(long id)
{
try
{
if (id == null)
return 0;
else
return (long)id;
}
catch (Exception)
{
return 0;
}
}
public static decimal GetNullToDecimal(decimal? id)
{
try
{
if (id == null)
return 0;
else
return (decimal)id;
}
catch (Exception)
{
return 0;
}
}
public static decimal GetNullToDecimal(string id)
{
try
{
if (string.IsNullOrEmpty(id))
return 0;
else
return Convert.ToDecimal(id);
}
catch (Exception)
{
return 0;
}
}
public static string GetNullToString(string name)
{
try
{
if (string.IsNullOrEmpty(name))
return "";
else
return name;
}
catch (Exception)
{
return "";
}
}
public static DateTime StringToDateTime(string time)
{
try
{
if (string.IsNullOrEmpty(time))
return Convert.ToDateTime("1870-01-01");
else
return Convert.ToDateTime(time);
}
catch (Exception)
{
return Convert.ToDateTime("1870-01-01");
}
}
public static string GetNullToDateTime(DateTime? date)
{
try
{
if (date.HasValue)
{
if (Convert.ToDateTime(date) == Convert.ToDateTime("1870-01-01"))
return "";
}
}
catch (Exception)
{
}
return "";
}
/// <summary>
/// SqlDataReader读取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="reader"></param>
/// <param name="field"></param>
/// <returns></returns>
public static T GetNullableReaderValue<T>(IDataReader reader, string field)
{
if (reader[field] == DBNull.Value)
return default(T);
return (T)reader[field];
///调用示例
//using (IDataReader reader = ExecuteDataReader(strSql.ToString(), pars))
//{
// while (reader.Read())
// {
// string result = GetNullableReaderValue<string>(reader, "PoNumber");
// }
//}
}
/// <summary>
/// DataRow读取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="row"></param>
/// <param name="field"></param>
/// <returns></returns>
public static T GetNullableDataRowValue<T>(DataRow row, string field)
{
if (row[field] == DBNull.Value)
return default(T);
return (T)row[field];
///调用示例
DataSet ds = Query(sqlString);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow item in ds.Tables[0].Rows)
{
decimal AssetMoney = GetNullableDataRowValue<decimal>(item, "Money");
int AssetUseYear = GetNullableDataRowValue<int>(item, "UseYear");
}
}
}
/// <summary>
/// 获取web.config的key值
/// </summary>
/// <param name="key"><add key="APIDomain" value="test" /></param>
/// <returns>test</returns>
public static string GetWebConfigKey(string key)
{
string result = string.Empty;
try
{
if (!string.IsNullOrEmpty(key))
result = ConfigurationManager.AppSettings[key];
}
catch (Exception)
{
}
return result;
}
/// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DelQuota(string str)
{
string result = str;
string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}
public static string GetSecuritySql(string str)
{
if (string.IsNullOrEmpty(str))
return str;
else
{
str = Regex.Replace(str, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
str = Regex.Replace(str, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"-->", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"<!--.*", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"&#(\d+);", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "xp_cmdshell", "", RegexOptions.IgnoreCase);
//删除与数据库相关的词
str = Regex.Replace(str, "select", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "insert", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "delete from", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "count''", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "drop table", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "asc", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "mid", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "char", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "xp_cmdshell", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "exec master", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "net localgroup administrators", "", RegexOptions.IgnoreCase);
//str = Regex.Replace(str, "and", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "net user", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"(\s+or)|(or\s+)", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "net", "", RegexOptions.IgnoreCase);
//str = Regex.Replace(str, "*", "", RegexOptions.IgnoreCase);
//str = Regex.Replace(str, "-", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "delete", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "update", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "exec", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "execute", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "drop", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "script", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "xp_", "x p_", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "sp_", "s p_", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "0x", "0 x", RegexOptions.IgnoreCase);
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="sWord">要写入日志里的文本内容</param>
public static void LogResult(string sWord)
{
string strPath = HttpContext.Current.Server.MapPath("log");
strPath = strPath + "\\" + DateTime.Now.ToString().Replace(":", "") + ".txt";
StreamWriter fs = new StreamWriter(strPath, false, System.Text.Encoding.Default);
fs.Write(sWord);
fs.Close();
}
/**
* 实际的写日志操作
* @param type 日志记录类型
* @param className 类名
* @param content 写入内容
*/
public static void WriteLog(string type, string className, string content)
{
//在网站根目录下创建日志目录
string path = HttpContext.Current.Request.PhysicalApplicationPath + "logs";
if (!Directory.Exists(path))//如果日志目录不存在就创建
{
Directory.CreateDirectory(path);
}
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
string filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名
//创建或打开日志文件,向日志文件末尾追加记录
StreamWriter mySw = File.AppendText(filename);
//向日志文件写入内容
string write_content = time + " " + type + " " + className + ": " + content;
mySw.WriteLine(write_content);
//关闭日志文件
mySw.Close();
}
#region URL请求数据
/// <summary>
/// HTTP POST方式请求数据
/// </summary>
/// <param name="url">URL.</param>
/// <param name="param">POST的数据</param>
/// <returns></returns>
public static string HttpPost(string url, string param)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
/// <summary>
/// HTTP GET方式请求数据.
/// </summary>
/// <param name="url">URL.</param>
/// <returns></returns>
public static string HttpGet(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
//request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
response = null;
}
return responseStr;
}
/// <summary>
/// 执行URL获取页面内容
/// </summary>
public static string UrlExecute(string urlPath)
{
if (string.IsNullOrEmpty(urlPath))
{
return "error";
}
StringWriter sw = new StringWriter();
try
{
HttpContext.Current.Server.Execute(urlPath, sw);
return sw.ToString();
}
catch (Exception)
{
return "error";
}
finally
{
sw.Close();
sw.Dispose();
}
}
/// <summary>
/// 检查是否是Guid类型
/// 调用方法:if (!StringPlus.IsGuidByParse(item.Pid)){}
/// </summary>
/// <param name="strSrc"></param>
/// <returns></returns>
public static bool IsGuidByParse(string strSrc)
{
Guid g = Guid.Empty;
return Guid.TryParse(strSrc, out g);
}
/// <summary>
/// 生成拼音简码
/// </summary>
/// <param name="unicodeString">Unicode编码字符串</param>
/// 调用示例: var name = StringPlus.GetPinyinCode("中国制造");
/// <returns></returns>
public static string GetPinyinCode(string unicodeString)
{
int i = 0;
ushort key = 0;
string strResult = string.Empty;
//创建两个不同的encoding对象
Encoding unicode = Encoding.Unicode;
//创建GBK码对象
Encoding gbk = Encoding.GetEncoding(936);
//将unicode字符串转换为字节
byte[] unicodeBytes = unicode.GetBytes(unicodeString);
//再转化为GBK码
byte[] gbkBytes = Encoding.Convert(unicode, gbk, unicodeBytes);
while (i < gbkBytes.Length)
{
//如果为数字\字母\其他ASCII符号
if (gbkBytes[i] <= 127)
{
strResult = strResult + (char)gbkBytes[i];
i++;
}
#region 否则生成汉字拼音简码,取拼音首字母
else
{
key = (ushort)(gbkBytes[i] * 256 + gbkBytes[i + 1]);
if (key >= '\uB0A1' && key <= '\uB0C4')
{
strResult = strResult + "A";
}
else if (key >= '\uB0C5' && key <= '\uB2C0')
{
strResult = strResult + "B";
}
else if (key >= '\uB2C1' && key <= '\uB4ED')
{
strResult = strResult + "C";
}
else if (key >= '\uB4EE' && key <= '\uB6E9')
{
strResult = strResult + "D";
}
else if (key >= '\uB6EA' && key <= '\uB7A1')
{
strResult = strResult + "E";
}
else if (key >= '\uB7A2' && key <= '\uB8C0')
{
strResult = strResult + "F";
}
else if (key >= '\uB8C1' && key <= '\uB9FD')
{
strResult = strResult + "G";
}
else if (key >= '\uB9FE' && key <= '\uBBF6')
{
strResult = strResult + "H";
}
else if (key >= '\uBBF7' && key <= '\uBFA5')
{
strResult = strResult + "J";
}
else if (key >= '\uBFA6' && key <= '\uC0AB')
{
strResult = strResult + "K";
}
else if (key >= '\uC0AC' && key <= '\uC2E7')
{
strResult = strResult + "L";
}
else if (key >= '\uC2E8' && key <= '\uC4C2')
{
strResult = strResult + "M";
}
else if (key >= '\uC4C3' && key <= '\uC5B5')
{
strResult = strResult + "N";
}
else if (key >= '\uC5B6' && key <= '\uC5BD')
{
strResult = strResult + "O";
}
else if (key >= '\uC5BE' && key <= '\uC6D9')
{
strResult = strResult + "P";
}
else if (key >= '\uC6DA' && key <= '\uC8BA')
{
strResult = strResult + "Q";
}
else if (key >= '\uC8BB' && key <= '\uC8F5')
{
strResult = strResult + "R";
}
else if (key >= '\uC8F6' && key <= '\uCBF9')
{
strResult = strResult + "S";
}
else if (key >= '\uCBFA' && key <= '\uCDD9')
{
strResult = strResult + "T";
}
else if (key >= '\uCDDA' && key <= '\uCEF3')
{
strResult = strResult + "W";
}
else if (key >= '\uCEF4' && key <= '\uD188')
{
strResult = strResult + "X";
}
else if (key >= '\uD1B9' && key <= '\uD4D0')
{
strResult = strResult + "Y";
}
else if (key >= '\uD4D1' && key <= '\uD7F9')
{
strResult = strResult + "Z";
}
else
{
strResult = strResult + "?";
}
i = i + 2;
}
#endregion
}
return strResult;
}
/// <summary>
/// 创建文件夹路径名称
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string CreatDirectoryPath(string path)
{
string result = string.Empty;
try
{
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
if (month.Length == 1)
month = "0" + month;
result = path + "/" + year + "/" + month + "/";
}
catch (Exception)
{
result = path;
}
return result;
}
#region JObject json操作
public void JObjectTest(string htmlTest)
{
///{
/// "code": 200,
/// "codemsg": "执行成功",
/// "data": {
/// "merchantOrderCode": "20190402170825908",
/// "error": 104,
/// "success": false,
/// "msg": "余额不足"
/// }
///}
JObject jsonResult = JObject.Parse(response);
#region 1级
var resultCode = jsonResult.Value<string>("code");
#endregion
#region 2级
var resultData = JObject.Parse(response)["data"];
var resultSuccess = resultData.Value<bool>("success");
#endregion
#region 方式1
var pid = JObject.Parse(htmlTest)["pid"];
var urlResult = JObject.Parse(htmlTest)["url"];
var errorResult = JObject.Parse(htmlTest)["error"];
#endregion
#region 方式2
JObject jsonResult = JObject.Parse(htmlTest);
var resultCode = jsonResult.Value<string>("code");
if (resultCode == "SUCCESS")
{
var cnt = jsonResult["content"];
#region 单条记录
UserContent model = (UserContent)JsonConvert.DeserializeObject(cnt.ToString(), typeof(UserContent));
UserContent content = JsonConvert.DeserializeObject<UserContent>(cnt.ToString());
#endregion
#region
List<UserContent> list = (List<UserContent>)JsonConvert.DeserializeObject(cnt.ToString(), typeof(List<UserContent>));
List<UserContent> objList = JsonConvert.DeserializeObject<List<UserContent>>(cnt.ToString());
#endregion
}
#endregion
}
public void JObjectToJsonString(string token, string cookies)
{
JObject jObject = new JObject();
jObject["token"] = JsonConvert.DeserializeObject<JObject>(token);
jObject["cookies"] = JsonConvert.DeserializeObject<JArray>(cookies);
JObject jObjectNew = new JObject();
jObjectNew.Add("token", JsonConvert.DeserializeObject<JObject>(token));
jObjectNew.Add("cookies", JsonConvert.DeserializeObject<JArray>(cookies));
string jsonString = jObjectNew.ToString(Formatting.None);//Formatting.None:字符串中不会空格,或者制表符
}
#endregion
public static string GetDoMain(string url)
{
try
{
int pos = url.IndexOf("//");
int pos2 = url.IndexOf("/", pos + 2);
return url.Substring(0, pos2);
}
catch { return ""; }
}
#endregion
}
}
字符串转Dictionary对象
public static Dictionary<object, object> GetConentByString(string data,string matchKey, string matchValue)
{
Dictionary<object, object> conents = new Dictionary<object, object>();
if (data.Substring(data.Length - 1) != matchValue)
{
data = data + matchValue;
}
try
{
int pos = 0;
int startIndex = 0;
while (true)
{
//Get Key
pos = data.IndexOf(matchKey, startIndex);
string key = data.Substring(startIndex, pos - startIndex);
startIndex = pos + 1;
//Get Value
pos = data.IndexOf(matchValue, startIndex);
string value = data.Substring(startIndex, pos - startIndex);
startIndex = pos + 1;
conents.Add(key, value);
if (startIndex >= data.Length)
{
break;
}
}
}
catch (Exception ex)
{
throw new Exception("Error Info: " + ex.ToString());
}
return conents;
}
调用
string jsonString = "start=,end=,barcodeStart=1,barcodeEnd=1,financesSart=2,financeEnd=2,moneyStart=22,moneyEnd=22";
string matchKey = "=";
string matchValue = ",";
Dictionary<object, object> codeList = StringPlus.GetConentByString(jsonString, matchKey, matchValue);
string start = Convert.ToString(codeList["start"]);
string end = Convert.ToString(codeList["end"]);