C# 我常用的myclass类库相关函数

发布时间:2009年06月18日      浏览次数:859 次
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Data;
using System.Windows.Forms;
namespace MyData.Inc
{
public class my_class
{
#region MD5加密 与 ES加密解密函数
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">要进行MD5加密的字符串</param>
/// <returns>加密成功返回加密后的字符串</returns>
public static string MD5(string str)
{
//获取str的byte类型数组
byte[] bytestr = Encoding.UTF8.GetBytes(str);
//实例化MD5CryptoServiceProvider
MD5CryptoServiceProvider myMD5 = new MD5CryptoServiceProvider();
// byte类型数组的值转换为 byte类型的MD5值
byte[] byteMD5str = myMD5.ComputeHash(bytestr);
//将byte类型的MD5值转换为字符串
string MD5_str = "";
for (int i = 0; i < byteMD5str.Length; i++)
{
MD5_str += byteMD5str[i].ToString("x").PadLeft(2, '0');
//大写的X,得到的MD5_str是大写字母和数字组成的字符串
//小写的x,得到的MD5_str是小写字母和数字组成的字符串
}
//返回MD5字符串
return MD5_str;
}
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="m_string">待加密的字符串</param>
/// <param name="m_key">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string Str_Encrypt(string m_string, string m_key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(m_key.Substring(0, 8));
byte[] rgbIV = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
byte[] inputByteArray = Encoding.UTF8.GetBytes(m_string);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return m_string;
}
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="m_string">待解密的字符串</param>
/// <param name="m_key">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string Str_Decrypt(string m_string, string m_key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(m_key.Substring(0, 8));
byte[] rgbIV = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
byte[] inputByteArray = Convert.FromBase64String(m_string);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return m_string;
}
}
#endregion
#region 读取、写入、复制、删除、移动、重命名文件
/// <summary>
/// 读取文本文件
/// </summary>
/// <param name="File_Path">要读取的文件路径</param>
/// <returns>返回读取的字符串</returns>
public static string File_read(string File_Path)
{
StringBuilder content = new StringBuilder();
if ( File.Exists(File_Path) )
{
StreamReader sr = new StreamReader(File_Path, System.Text.Encoding.GetEncoding("gb2312"));
//StreamReader sr = new StreamReader(File_Path);
//string lineText;
do
{
content.Append(sr.ReadLine() + "\n");
//lineText = sr.ReadLine();
//if (lineText != "")
//{
// content.Append(lineText+"\n");
//}
} while (sr.Peek() != -1);
sr.Close();
}
return content.ToString();
}
/// <summary>
/// 写入文本文件
///</summary>
/// <param name="File_Path">要写入的文件路径</param>
/// <param name="content">要写入的字符串内容</param>
/// <returns></returns>
public static void File_write(string File_Path, string content)
{
StreamWriter sw = null;
sw = File.CreateText(File_Path);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
/// <summary>
/// 复制文件
///</summary>
/// <param name="Source_Path">要复制的源文件路径</param>
/// <param name="Target_Path">要复制到的目标路径</param>
/// <returns>返回结果true,false</returns>
public static void File_copy(string Source_Path, string Target_Path)
{
// 判断目标目录是否存在如果不存在则新建之
string Target_Folder = Target_Path.Substring(0, Target_Path.LastIndexOf(@""));
if (!System.IO.Directory.Exists(Target_Folder))
{
System.IO.Directory.CreateDirectory(Target_Folder); //如果目标文件夹不存在,则创建
}
try
{
System.IO.File.Copy(Source_Path, Target_Path, true); //复制文件
}
catch {}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="File_Path">要删除的文件路径</param>
/// <returns></returns>
public static void File_delete(string File_Path)
{
try
{
if (File.Exists(File_Path.Trim()))
{
File.Delete(File_Path.Trim());
}
}
catch {}
}
/// <summary>
/// 移动文件
///</summary>
/// <param name="Source_Path">要移动的源文件路径</param>
/// <param name="Target_Path">要移动到的目标路径</param>
/// <returns></returns>
public static void File_move(string Source_Path, string Target_Path)
{
//if (Source_Path.Trim() == Target_Path.Trim()) return;//如果源和目标路径相同,则不操作

////判断目标目录是否存在如果不存在则新建之
//string Target_Folder = Target_Path.Substring(0, Target_Path.LastIndexOf(@""));
//if (!System.IO.Directory.Exists(Target_Folder))
//{
// System.IO.Directory.CreateDirectory(Target_Folder); //如果目标文件夹不存在,则创建
//}
//try
//{
// if (File.Exists(Source_Path))
// {
// System.IO.File.Move(@Source_Path, @Target_Path); //移动文件
// }
//}
//catch { }
}
/// <summary>
/// 重命名文件
/// </summary>
/// <param name="File_Path">要重命名的源文件路径</param>
/// <param name="New_Name">新文件名</param>
/// <returns></returns>
public static void File_rename(string File_Path, string New_Name)
{
//if (System.IO.Path.GetFileName(File_Path.Trim()) == New_Name.Trim()) return;//如果旧文件名与新的文件名相同,则不操作
//// 判断源文件目录是否存在
//if (File.Exists(File_Path))
//{
// string Folder = File_Path.Substring(0, File_Path.LastIndexOf(@""));//取得源文件的文件夹
// // 检查目录是否以目录分割字符结束如果不是则添加之
// if (Folder[Folder.Length - 1] != System.IO.Path.DirectorySeparatorChar)
// {
// Folder += System.IO.Path.DirectorySeparatorChar;
// }
// try
// {
// System.IO.File.Move(@File_Path, @Folder + @New_Name); //重命名
// }
// catch { }
//}
}
#endregion
#region 创建、删除、复制文件夹
/// <summary>
/// 创建文件夹
///</summary>
/// <param name="Folder_Path">要创建的文件夹路径</param>
/// <returns></returns>
public static void Folder_create(string Folder_Path)
{
try
{
//如果文件夹不存在,则创建
if (!System.IO.Directory.Exists(Folder_Path))
{
System.IO.Directory.CreateDirectory(Folder_Path);
}
}
catch {}
}
/// <summary>
/// 删除文件夹
///</summary>
/// <param name="Folder_Path">要删除的文件夹路径</param>
/// <returns></returns>
public static void Folder_delete(string Folder_Path)
{
try
{
if (System.IO.Directory.Exists(Folder_Path))
{
foreach (string file in Directory.GetFileSystemEntries(Folder_Path))
{
if (File.Exists(file))
{
FileInfo FI = new FileInfo(file);
if (FI.Attributes.ToString().IndexOf("ReadOnly") != -1)
FI.Attributes = FileAttributes.Normal;
File.Delete(file);//直接删除其中的文件
}
else
Folder_delete(file);//递归删除子文件夹
}
Directory.Delete(Folder_Path);//删除已空文件夹
}
}
catch {}
}
/// <summary>
/// 复制文件夹
///</summary>
/// <param name="Source_Path">要复制的源文件夹路径</param>
/// <param name="Target_Path">要复制到的目标文件夹路径</param>
/// <returns></returns>
public static void Folder_copy(string Source_Path, string Target_Path)
{
if (!System.IO.Directory.Exists(Source_Path) || Source_Path.Trim() == Target_Path.Trim()) return;//如果源文件夹不存在或源与目标文件夹名相同,则不操作
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (Target_Path[Target_Path.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
Target_Path += System.IO.Path.DirectorySeparatorChar;
}
// 判断目标目录是否存在如果不存在则新建之
if (!System.IO.Directory.Exists(Target_Path))
{
System.IO.Directory.CreateDirectory(Target_Path);
}
if (System.IO.Directory.Exists(Source_Path))
{
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
// string[] fileList = Directory.GetFiles(Source_Path);
string[] fileList = System.IO.Directory.GetFileSystemEntries(Source_Path);
// 遍历所有的文件和目录
foreach (string file in fileList)
{
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (System.IO.Directory.Exists(file))
{
Folder_copy(file, Target_Path + System.IO.Path.GetFileName(file));
}
// 否则直接Copy文件
else
{
System.IO.File.Copy(file, Target_Path + System.IO.Path.GetFileName(file), true);
}
}
}
}
catch {}
}
/// <summary>
/// 移动文件夹
///</summary>
/// <param name="Source_Path">要移动的源文件夹路径</param>
/// <param name="Target_Path">要移动到的目标文件夹路径</param>
/// <returns></returns>
public static void Folder_move(string Source_Path, string Target_Path)
{
//if (!System.IO.Directory.Exists(Source_Path) || Source_Path.Trim() == Target_Path.Trim()) return;//如果源文件夹不存在或源与目标文件夹名相同,则不操作
//try
//{
// // 判断目标目录是否存在如果不存在则新建之
// if (!System.IO.Directory.Exists(Target_Path))
// {
// System.IO.Directory.CreateDirectory(Target_Path);
// }
// try
// {
// System.IO.Directory.Move(Source_Path, Target_Path); //移动目录
// }
// catch { }
//}
//catch { }
}
/// <summary>
/// 重命名文件夹
///</summary>
/// <param name="Source_Path">要重命名的源文件夹路径</param>
/// <param name="New_Name">新文件夹名</param>
/// <returns></returns>
public static void Folder_rename(string Source_Path, string New_Name)
{
//if (!System.IO.Directory.Exists(Source_Path)) return;//如果源文件夹不存在,则不操作
//try
//{
// //获取源文件夹的上级目录路径
// string Folder_Path = Source_Path.Substring(0, Source_Path.LastIndexOf(@""));
// // 检查目标目录是否以目录分割字符结束如果不是则添加之
// if (Folder_Path[Folder_Path.Length - 1] != System.IO.Path.DirectorySeparatorChar)
// {
// Folder_Path += System.IO.Path.DirectorySeparatorChar;
// }
// string New_Folder_Path = Folder_Path + New_Name; //新文件夹的路径
// //如果源与目标文件夹路径相同,则不操作
// if (Source_Path.Trim() == New_Folder_Path.Trim()) return;
// // 判断目标目录是否存在如果不存在则新建之
// if (!System.IO.Directory.Exists(New_Folder_Path))
// {
// System.IO.Directory.CreateDirectory(New_Folder_Path);
// }
// try
// {
// System.IO.Directory.Move(@Source_Path, @New_Folder_Path); //移动目录相当于重命名
// }
// catch { }
//}
//catch { }
}
#endregion
#region 相关验证函数
/// <summary>
/// 验证输入字符串是否为日期
/// </summary>
/// <param name="strDate">要进行验证的字符串</param>
/// <returns>返回True或False</returns>
public static bool is_Date(string strDate)
{
DateTime dtDate;
bool bValid = true;
try
{
dtDate = DateTime.Parse(strDate);
}
catch (FormatException)
{
// 如果解析方法失败则表示不是日期性数据
bValid = false;
}
return bValid;
}
/// <summary>
/// 验证输入字符串是否为数字
/// </summary>
/// <param name="strNumber">要进行验证的字符串</param>
/// <returns>返回True或False</returns>
public static bool is_Numeric(string strNumber)
{
try
{
Double.Parse(strNumber);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 验证输入字符串是否为E-mail地址
/// </summary>
/// <param name="str_email">要进行验证的字符串</param>
/// <returns>返回True或False</returns>
public static bool is_Email(string str_email)
{
return Regex.IsMatch(str_email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}
/// <summary>
/// 验证输入字符串是否为网络地址
/// </summary>
/// <param name="str_naddress">要进行验证的字符串</param>
/// <returns>返回True或False</returns>
public static bool is_Http_url(string str_naddress)
{
return Regex.IsMatch(str_naddress, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
}
#endregion
#region 系统通用传递参数类Session
public class Context
{
public static Hashtable ContextData = new Hashtable();
}
#region 字符串保存变量
/// <summary>
/// 创建或设置Session变量值
/// </summary>
/// <param name="str_name">变量名称</param>
/// <param name="str_value">值</param>
/// <returns></returns>
public static void Session(string str_name, string str_value)
{
if (!Context.ContextData.ContainsKey(str_name))
{
Context.ContextData.Add(str_name, str_value);
}
else
{
Context.ContextData[str_name] = str_value;
}
}
/// <summary>
/// 获取Session变量值
/// </summary>
/// <param name="str_name">变量名称</param>
/// <returns>返回变量的值</returns>
public static string Session(string str_name)
{
try
{
return (string)Context.ContextData[str_name];
}
catch
{
return "";
}
}
#endregion
//----------------------------------------------------------
#region 窗体对象保存变量
/// <summary>
/// 创建或设置Form_Session变量值
/// </summary>
/// <param name="str_name">变量名称</param>
/// <param name="str_value">值</param>
/// <returns></returns>
public static void Form_Session(string Form_name, Form Form_Object)
{
if (!Context.ContextData.ContainsKey(Form_name))
{
Context.ContextData.Add(Form_name, Form_Object);
}
else
{
Context.ContextData[Form_name] = Form_Object;
}
}
/// <summary>
/// 获取Form_Session变量值
/// </summary>
/// <param name="str_name">变量名称</param>
/// <returns>返回变量的值</returns>
public static Form Form_Session(string Form_name)
{
try
{
return (Form)Context.ContextData[Form_name];
}
catch
{
return null;
}
}
#endregion
#endregion
#region 获取远程URL的相关数据
/// <summary>
/// 获取远程URL的相关数据
/// <summary>
/// <param name="url">网址</param>
/// <returns>返回获取的字符串</returns>
public static string Get_url_data(string url)
{
string Url_Data = "";
try
{
System.Net.WebRequest Request = System.Net.WebRequest.Create(url);
System.Net.WebResponse Response = Request.GetResponse();
System.IO.Stream resStream = Response.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(resStream, System.Text.Encoding.Default);
Url_Data = sr.ReadToEnd();
resStream.Close();
sr.Close();
}
catch { }
return Url_Data.Trim();
}
#endregion
#region 日期时间相关函数
/// <summary>
/// 将Unix时间戳转换为DateTime类型时间
/// </summary>
/// <param name="d">double 型数字</param>
/// <returns>返回时间DateTime</returns>
public static System.DateTime Int_to_Date(double d)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddSeconds(d);
return time;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">DateTime时间</param>
/// <returns>返回double型的数字</returns>
public static double Date_to_Int(System.DateTime time)
{
double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (time - startTime).TotalSeconds;
return intResult;
}
/// <summary>
/// 计算本周起始日期(礼拜一的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime Get_Monday(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Subtract(ts);
}
/// <summary>
/// 计算本周结束日期(礼拜日的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜日日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime Get_Sunday(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Sunday;
if (i != 0) i = 7 - i;// 因为枚举原因,Sunday排在最前,相减间隔要被7减。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Add(ts);
}
/// <summary>
/// 判断选择的日期是否是本周(根据系统当前时间决定的‘本周’比较而言)
/// </summary>
/// <param name="someDate">任意一天</param>
/// <returns>返回True或False</returns>
public static bool is_ThisWeek(DateTime someDate)
{
//得到someDate对应的周一
DateTime someMon = Get_Monday(someDate);
//得到本周一
DateTime nowMon = Get_Sunday(DateTime.Now);
TimeSpan ts = someMon - nowMon;
if (ts.Days < 0)
ts = -ts;//取正
if (ts.Days >= 7)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 根据日期返回星期
/// </summary>
/// <param name="SomeDate">任意一天的日期</param>
/// <param name="WeekType">返回“中文”、“英文”或“数字”的星期值</param>
/// <returns>返回星期</returns>
public static string Get_Week(string SomeDate, string WeekType)
{
string strWeek = "";
try
{
DateTime day = Convert.ToDateTime(SomeDate.Trim());
if (WeekType == "英文")
{
strWeek = day.DayOfWeek.ToString();//英文星期
}
else if (WeekType == "数字")
{
int int_week = (int)day.DayOfWeek;//星期数字
strWeek = int_week.ToString().Trim();
}
else
{
//中文星期
System.Globalization.CultureInfo CTI = new System.Globalization.CultureInfo("zh-CN");
strWeek = "星期" + CTI.DateTimeFormat.GetAbbreviatedDayName(day.DayOfWeek).ToString();
}
}
catch {}
return strWeek;
}
#endregion
#region 字符串相关函数
/// <summary>
/// 截取指定长度的中英文混合字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="length">截取长度,int型,以字节为单位</param>
/// <returns>返回截取的字符串</returns>
public static string Str_Left(string str, int length)
{
Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
char[] stringChar = str.ToCharArray();
StringBuilder sb = new StringBuilder();
int nLength = 0;
bool isCut = false;
for (int i = 0; i < stringChar.Length; i++)
{
if (regex.IsMatch((stringChar[i]).ToString()))
{
sb.Append(stringChar[i]);
nLength += 2;
}
else
{
sb.Append(stringChar[i]);
nLength = nLength + 1;
}
if (nLength > length)
{
isCut = true;
break;
}
}
if (isCut)
return sb.ToString() + "..";
else
return sb.ToString();
}
#endregion
//过滤提交信息中的单引号“'”,将其转换为“'”
public static string Text_过滤单引号(string str)
{
return str.Replace("'", "’");
}
public static string Text_反过滤字符串(string str)
{
str = str.Replace("", "");
str = str.Replace(" ", " ");
str = str.Replace("'", "’");
str = str.Replace(""", """);
return str;
}

#region 判断是否连接了网络
public const int INTERNET_CONNECTION_MODEM = 1;
public const int INTERNET_CONNECTION_LAN = 2;
[System.Runtime.InteropServices.DllImport("winInet.dll")]
public static extern bool InternetGetConnectedState(
ref int dwFlag,
int dwReserved
);
/*
调用示例
System.Int32 dwFlag = new int();
if (!my_class.InternetGetConnectedState(ref dwFlag, 0))
{
MessageBox.Show("网络未连接,请检查!", "提示");
return;
}
else
{
if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
{
MessageBox.Show("采用调制解调器上网。");
}
else
{
if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
{
MessageBox.Show("采用网卡上网。");
}
}
}
*/
#endregion
#region 强制关闭进程
/// 运行DOS命令,DOS关闭进程命令(ntsd -c q -p PID )PID为进程的ID
/// 调用示例(关闭自身的进程)
/// string exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
/// string[] exeArray = exeName.Split('');
/// my_class.强制关闭进程("taskkill /im " + exeArray[exeArray.Length - 1] + " /f ");
public static string 强制关闭进程(string command)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
return p.StandardOutput.ReadToEnd();
}
#endregion
}
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!